Text stringlengths 1 9.41k |
|---|
As mentioned earlier, our discussion of some of the more advanced class tools continues in the final part of this book;
be sure to look ahead if you need more details on properties, descriptors, decorators,
and metaclasses.
This is the end of the class part of this book, so you’ll find the usual lab exercises at the
e... |
In the next chapter, we’ll begin our look at our last core language topic, exceptions. Exceptions are Python’s mechanism for communicating errors and other
conditions to your code. |
This is a relatively lightweight topic, but I’ve saved it for last
because exceptions are supposed to be coded as classes today. |
Before we tackle that
final core subject, though, take a look at this chapter’s quiz and the lab exercises.
###### Test Your Knowledge: Quiz
1. Name two ways to extend a built-in object type.
2. |
What are function decorators used for?
3. How do you code a new-style class?
4. How are new-style and classic classes different?
5. How are normal and static methods different?
6. |
How long should you wait before lobbing a “Holy Hand Grenade”?
###### Test Your Knowledge: Answers
1. You can embed a built-in object in a wrapper class, or subclass the built-in type
directly. |
The latter approach tends to be simpler, as most original behavior is automatically inherited.
2. |
Function decorators are generally used to add to an existing function a layer of
logic that is run each time the function is called. |
They can be used to log or count
calls to a function, check its argument types, and so on. |
They are also used to
“declare” static methods—simple functions in a class that are not passed an instance when called.
**|**
-----
3. |
New-style classes are coded by inheriting from the `object built-in class (or any`
other built-in type). |
In Python 3.0, all classes are new-style automatically, so this
derivation is not required; in 2.6, classes with this derivation are new-style and
those without it are “classic.”
4. |
New-style classes search the diamond pattern of multiple inheritance trees differently—they essentially search breadth-first (across), instead of depth-first (up).
New-style classes also change the result of the `type built-in for instances and`
classes, do not run generic attribute fetch methods such as __getattr__ fo... |
Normal (instance) methods receive a self argument (the implied instance), but
static methods do not. |
Static methods are simple functions nested in class objects.
To make a method static, it must either be run through a special built-in function
or be decorated with decorator syntax. |
Python 3.0 allows simple functions in a
class to be called through the class without this step, but calls through instances
still require static method declaration.
6. Three seconds. |
(Or, more accurately: “And the Lord spake, saying, ‘First shalt thou
take out the Holy Pin. Then, shalt thou count to three, no more, no less. |
Three
shalt be the number thou shalt count, and the number of the counting shall be
three. Four shalt thou not count, nor either count thou two, excepting that thou
then proceed to three. |
Five is right out. |
Once the number three, being the third
number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards
thy foe, who, being naughty in my sight, shall snuff it.’”)[*]
###### Test Your Knowledge: Part VI Exercises
These exercises ask you to write a few classes and experiment with some existing code.
Of c... |
To work with the
set class in exercise 5, either pull the class source code off this book’s website (see the
Preface for a pointer) or type it up by hand (it’s fairly brief). |
These programs are starting
to get more sophisticated, so be sure to check the solutions at the end of the book for
pointers. |
You’ll find them in Appendix B, under “Part VI, Classes and
OOP” on page 1122.
1. Inheritance. Write a class called Adder that exports a method add(self, x, y) that
prints a “Not Implemented” message. |
Then, define two subclasses of Adder that
implement the add method:
```
ListAdder
```
With an add method that returns the concatenation of its two list arguments
- This quote is from Monty Python and the Holy Grail.
**|**
-----
```
DictAdder
```
With an add method that returns a new dictionary containing the ... |
Where is the best place to put the constructors and
```
operator overloading methods (i.e., in which classes)? |
What sorts of objects can
you add to your class instances?
In practice, you might find it easier to code your add methods to accept just one
real argument (e.g., `add(self,y)), and add that one argument to the instance’s`
current data (e.g., self.data + y). |
Does this make more sense than passing two
arguments to add? Would you say this makes your classes more “object-oriented”?
2. Operator overloading. |
Write a class called Mylist that shadows (“wraps”) a Python
list: it should overload most list operators and operations, including +, indexing,
iteration, slicing, and list methods such as append and sort. |
See the Python reference
manual for a list of all possible methods to support. |
Also, provide a constructor
for your class that takes an existing list (or a Mylist instance) and copies its components into an instance member. Experiment with your class interactively. |
Things
to explore:
a. Why is copying the initial value important here?
b. Can you use an empty slice (e.g., start[:]) to copy the initial value if it’s a
```
Mylist instance?
```
c. |
Is there a general way to route list method calls to the wrapped list?
d. Can you add a Mylist and a regular list? How about a list and a Mylist instance?
e. |
What type of object should operations like + and slicing return? What about
indexing operations?
f. |
If you are working with a more recent Python release (version 2.2 or later), you
may implement this sort of wrapper class by embedding a real list in a standalone class, or by extending the built-in list type with a subclass. |
Which is
easier, and why?
3. Subclassing. |
Make a subclass of `Mylist from exercise 2 called` `MylistSub, which`
extends Mylist to print a message to stdout before each overloaded operation is
called and counts the number of calls. |
MylistSub should inherit basic method behavior from `Mylist. Adding a sequence to a` `MylistSub should print a message,`
increment the counter for + calls, and perform the superclass’s method. |
Also, introduce a new method that prints the operation counters to stdout, and experiment
with your class interactively. |
Do your counters count calls per instance, or per class
(for all instances of the class)? |
How would you program the other option)?
**|**
-----
(Hint: it depends on which object the count members are assigned to: class members are shared by instances, but self members are per-instance data.)
4. |
Metaclass methods. Write a class called `Meta with methods that intercept every`
attribute qualification (both fetches and assignments), and print messages listing
their arguments to stdout. |
Create a Meta instance, and experiment with qualifying
it interactively. What happens when you try to use the instance in expressions? Try
adding, indexing, and slicing the instance of your class. |
(Note: a fully generic approach based upon __getattr__ will work in 2.6 but not 3.0, for reasons noted in
Chapter 30 and restated in the solution to this exercise.)
5. Set objects. |
Experiment with the set class described in “Extending Types by Embedding” on page 774. Run commands to do the following sorts of operations:
a. |
Create two sets of integers, and compute their intersection and union by using
```
& and | operator expressions.
```
b. Create a set from a string, and experiment with indexing your set. |
Which
methods in the class are called?
c. Try iterating through the items in your string set using a `for loop. Which`
methods run this time?
d. |
Try computing the intersection and union of your string set and a simple Python string. Does it work?
e. |
Now, extend your set by subclassing to handle arbitrarily many operands using
the *args argument form. |
(Hint: see the function versions of these algorithms
in Chapter 18.) Compute intersections and unions of multiple operands with
your set subclass. |
How can you intersect three or more sets, given that & has
only two sides?
f. How would you go about emulating other list operations in the set class? |
(Hint:
```
__add__ can catch concatenation, and __getattr__ can pass most list method
```
calls to the wrapped list.)
6. Class tree links. |
In “Namespaces: The Whole Story” on page 693 in Chapter 28
and in “Multiple Inheritance: “Mix-in” Classes” on page 756 in Chapter 30, I
mentioned that classes have a __bases__ attribute that returns a tuple of their superclass objects (the ones listed in parentheses in the class header). |
Use
```
__bases__ to extend the lister.py mix-in classes we wrote in Chapter 30 so that they
```
print the names of the immediate superclasses of the instance’s class. |
When you’re
done, the first line of the string representation should look like this (your address
may vary):
```
<Instance of Sub(Super, Lister), address 7841200:
```
7. Composition. |
Simulate a fast-food ordering scenario by defining four classes:
```
Lunch
```
A container and controller class
**|**
-----
```
Customer
```
The actor who buys food
```
Employee
```
The actor from whom a customer orders
```
Food
```
What the customer buys
To get you started, here are the classes and methods yo... |
The `Lunch class’s constructor should make and embed an instance of`
```
Customer and an instance of Employee, and it should export a method called
order. |
When called, this order method should ask the Customer to place an
```
order by calling its `placeOrder method. |
The` `Customer’s` `placeOrder method`
should in turn ask the `Employee object for a new` `Food object by calling`
```
Employee’s takeOrder method.
```
b. |
Food objects should store a food name string (e.g., “burritos”), passed down
from Lunch.order, to Customer.placeOrder, to Employee.takeOrder, and finally
to Food’s constructor. |
The top-level Lunch class should also export a method
called result, which asks the customer to print the name of the food it received
from the Employee via the order (this can be used to test your simulation).
Note that Lunch needs to pass either the Employee or itself to the Customer to allow
the Customer to call Emp... |
If you prefer, you can also simply
code test cases as self-test code in the file where your classes are defined, using the
module __name__ trick of Chapter 24. |
In this simulation, the Customer is the active
agent; how would your classes change if Employee were the object that initiated
customer/employee interaction instead?
**|**
-----
_Figure 31-1. |
A zoo hierarchy composed of classes linked into a tree to be searched by attribute_
_inheritance. |
Animal has a common “reply” method, but each class may have its own custom “speak”_
_method called by “reply”._
3. Zoo animal hierarchy. |
Consider the class tree shown in Figure 31-1.
Code a set of six class statements to model this taxonomy with Python inheritance.
Then, add a speak method to each of your classes that prints a unique message,
and a `reply method in your top-level` `Animal superclass that simply calls`
```
self.speak to invoke the cate... |
Finally, remove the`
```
speak method from your Hacker class so that it picks up the default above it. |
When
```
you’re finished, your classes should work this way:
```
% python
>>> from zoo import Cat, Hacker
>>> spot = Cat()
```
`>>> spot.reply()` _# Animal.reply; calls Cat.speak_
```
meow
```
`>>> data = Hacker()` _# Animal.reply; calls Primate.speak_
```
>>> data.reply()
Hello world!
... |
The Dead Parrot Sketch. Consider the object embedding structure captured in
Figure 31-2.
Code a set of Python classes to implement this structure with composition. |
Code
your Scene object to define an action method, and embed instances of the Customer,
```
Clerk, and Parrot classes (each of which should define a line method that prints
```
a unique message). |
The embedded objects may either inherit from a common superclass that defines line and simply provide message text, or define line themselves. |
In the end, your classes should operate like this:
```
% python
>>> import parrot
```
`>>> parrot.Scene().action()` _# Activate nested objects_
```
customer: "that's one ex-bird!"
```
**|**
-----
```
clerk: "no it isn't..."
parrot: None
```
_Figure 31-2. |
A scene composite with a controller class (Scene) that embeds and directs instances of_
_three other classes (Customer, Clerk, Parrot). |
The embedded instance’s classes may also participate_
_in an inheritance hierarchy; composition and inheritance are often equally useful ways to structure_
_classes for code reuse._
###### Why You Will Care: OOP by the Masters
When I teach Python classes, I invariably find that about halfway through the class,
people... |
The point behind the
technology just isn’t apparent.
In a book like this, I have the luxury of including material like the new Big Picture
overview in Chapter 25, and the gradual tutorial of Chapter 27—in fact, you should
probably review that section if you’re starting to feel like OOP is just some computer
science mu... |
The
answers they’ve given might help shed some light on the purpose of OOP, if you’re new
to the subject.
Here, then, with only a few embellishments, are the most common reasons to use OOP,
as cited by my students over the years:
_Code reuse_
This one’s easy (and is the main reason for using OOP). |
By supporting inheritance,
classes allow you to program by customization instead of starting each project from
scratch.
_Encapsulation_
Wrapping up implementation details behind object interfaces insulates users of a
class from code changes.
_Structure_
Classes provide new local scopes, which minimizes name clashes. |
They also provide a natural place to write and look for implementation code, and to manage
object state.
**|**
-----
**|**
-----
##### PART VII
## Exceptions and Tools
-----
-----
###### CHAPTER 32
### Exception Basics
This part of the book deals with exceptions, which are events that can modify the flow
of... |
In Python, exceptions are triggered automatically on
errors, and they can be triggered and intercepted by your code. |
They are processed by
four statements we’ll study in this part, the first of which has two variations (listed
separately here) and the last of which was an optional extension until Python 2.6 and
3.0:
```
try/except
```
Catch and recover from exceptions raised by Python, or by you.
```
try/finally
```
Perform cleanup... |
With a few exceptions (pun intended), though,
you’ll find that exception handling is simple in Python because it’s integrated into the
language itself as another high-level tool.
###### Why Use Exceptions?
In a nutshell, exceptions let us jump out of arbitrarily large chunks of a program. |
Consider the hypothetical pizza-making robot we discussed earlier in the book. Suppose
we took the idea seriously and actually built such a machine. |
To make a pizza, our
culinary automaton would need to execute a plan, which we would implement as a
-----
Python program: it would take an order, prepare the dough, add toppings, bake the
pie, and so on.
Now, suppose that something goes very wrong during the “bake the pie” step. |
Perhaps
the oven is broken, or perhaps our robot miscalculates its reach and spontaneously
combusts. |
Clearly, we want to be able to jump to code that handles such states quickly.
As we have no hope of finishing the pizza task in such unusual cases, we might as well
abandon the entire plan.
That’s exactly what exceptions let you do: you can jump to an exception handler in a
single step, abandoning all function calls b... |
Code in the exception handler can then respond to the raised exception as appropriate (by calling the fire department, for instance!).
One way to think of an exception is as a sort of structured “super go to.” An exception
_handler (try statement) leaves a marker and executes some code. |
Somewhere further_
ahead in the program, an exception is raised that makes Python jump back to that
marker, abandoning any active functions that were called after the marker was left.
This protocol provides a coherent way to respond to unusual events. |
Moreover, because
Python jumps to the handler statement immediately, your code is simpler—there is
usually no need to check status codes after every call to a function that could possibly
fail.
###### Exception Roles
In Python programs, exceptions are typically used for a variety of purposes. |
Here are
some of their most common roles:
_Error handling_
Python raises exceptions whenever it detects errors in programs at runtime. |
You
can catch and respond to the errors in your code, or ignore the exceptions that are
raised. |
If an error is ignored, Python’s default exception-handling behavior kicks
in: it stops the program and prints an error message. |
If you don’t want this default
behavior, code a try statement to catch and recover from the exception—Python
will jump to your try handler when the error is detected, and your program will
resume execution after the try.
_Event notification_
Exceptions can also be used to signal valid conditions without you having to p... |
For instance, a search routine
might raise an exception on failure, rather than returning an integer result code
(and hoping that the code will never be a valid result).
_Special-case handling_
Sometimes a condition may occur so rarely that it’s hard to justify convoluting your
code to handle it. |
You can often eliminate special-case code by handling unusual
cases in exception handlers in higher levels of your program.
**|**
-----
_Termination actions_
As you’ll see, the `try/finally statement allows you to guarantee that required`
closing-time operations will be performed, regardless of the presence or abse... |
For instance, although the language does not explicitly support backtracking, it can be implemented in Python
by using exceptions and a bit of support logic to unwind assignments.[*] There is no
“go to” statement in Python (thankfully!), but exceptions can sometimes serve
similar roles.
We’ll see such typical use case... |
For now, let’s
get started with a look at Python’s exception-processing tools.
###### Exceptions: The Short Story
Compared to some other core language topics we’ve met in this book, exceptions are
a fairly lightweight tool in Python. |
Because they are so simple, let’s jump right into
some code.
###### Default Exception Handler
Suppose we write the following function:
```
>>> def fetcher(obj, index):
... |
return obj[index]
...
```
There’s not much to this function—it simply indexes an object on a passed-in index.
In normal operation, it returns the result of a legal index:
```
>>> x = 'spam'
```
`>>> fetcher(x, 3)` _# Like x[3]_
```
'm'
```
However, if we ask this function to index off the end of the string, an... |
Python detects out-of-bounds indexing for sequences and reports it by _raising (triggering) the built-in_ `IndexError`
exception:
- True backtracking is an advanced topic that is not part of the Python language, so I won’t say much more
about it here (even the generator functions and expressions we met in Chapter 20 a... |
Roughly, backtracking undoes all computations before it jumps;
Python exceptions do not (i.e., variables assigned between the time a try statement is entered and the time
an exception is raised are not reset to their prior values). |
See a book on artificial intelligence or the Prolog or
Icon programming languages if you’re curious.
**|**
-----
`>>> fetcher(x, 4)` _# Default handler - shell interface_
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fetcher
IndexError: string index ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.