Text
stringlengths
1
9.41k
Python also comes with a module named shelve, which would allow you to store the pickled representation of the class instances in an accessby-key filesystem; the third-party open source ZODB system does the same but has better support for production-quality object-oriented databases. **|** ----- ``` data = co...
# Default behavior and tools def other(self): ... class FileReader(Reader): def read(self): ... # Read from a local file class SocketReader(Reader): def read(self): ...
# Read from a network socket ... processor(FileReader(...), Converter, FileWriter(...)) processor(SocketReader(...), Converter, TapeWriter(...)) processor(FtpReader(...), Converter, XmlWriter(...)) ``` Moreover, because the internal implementations of those read and write methods have been factored into sing...
In fact, the processor function might itself be a class to allow the conversion logic of converter to be filled in by inheritance, and to allow readers and writers to be embedded by composition (we’ll see how this works later in this part of the book). Once you get used to programming this way (by software customizati...
For example, someone else might have written the Employee, Reader, and Writer classes in this example for use in a completely different program.
If so, you get all of that person’s code “for free.” In fact, in many application domains, you can fetch or purchase collections of superclasses, known as frameworks, that implement common programming tasks as classes, ready to be mixed into your applications.
These frameworks might provide database interfaces, testing protocols, GUI toolkits, and so on.
With frameworks, you often simply code a subclass that fills in an expected method or two; the framework classes higher in the tree do most of the work for you.
Programming in such an OOP world is just a matter of combining and specializing already debugged code by writing subclasses of your own. Of course, it takes a while to learn how to leverage classes to achieve such OOP utopia. In practice, object-oriented work also entails substantial design work to fully realize the c...
The actual code you write to do OOP in Python, though, is so simple that it will not in itself pose an additional obstacle to your OOP quest.
To see why, you’ll have to move on to Chapter 26. **f** **|** ----- ###### Chapter Summary We took an abstract look at classes and OOP in this chapter, taking in the big picture before we dive into syntax details.
As we’ve seen, OOP is mostly about looking up attributes in trees of linked objects; we call this lookup an inheritance search.
Objects at the bottom of the tree inherit attributes from objects higher up in the tree—a feature that enables us to program by customizing code, rather than changing it, or starting from scratch.
When used well, this model of programming can cut development time radically. The next chapter will begin to fill in the coding details behind the picture painted here. As we get deeper into Python classes, though, keep in mind that the OOP model in Python is very simple; as I’ve already stated, it’s really just about...
Before we move on, here’s a quick quiz to review what we’ve covered here. ###### Test Your Knowledge: Quiz 1. What is the main point of OOP in Python? 2.
Where does an inheritance search look for an attribute? 3. What is the difference between a class object and an instance object? 4. Why is the first argument in a class method function special? 5.
What is the __init__ method used for? 6. How do you create a class instance? 7. How do you create a class? 8. How do you specify a class’s superclasses? ###### Test Your Knowledge: Answers 1.
OOP is about code reuse—you factor code to minimize redundancy and program by customizing what already exists instead of changing code in-place or starting from scratch. 2.
An inheritance search looks for an attribute first in the instance object, then in the class the instance was created from, then in all higher superclasses, progressing from the bottom to the top of the object tree, and from left to right (by default). The search stops at the first place the attribute is found.
Because the lowest version of a name found along the way wins, class hierarchies naturally support customization by extension. **|** ----- 3.
Both class and instance objects are namespaces (packages of variables that appear as attributes). The main difference between them is that classes are a kind of factory for creating multiple instances.
Classes also support operator overloading methods, which instances inherit, and treat any functions nested within them as special methods for processing instances. 4.
The first argument in a class method function is special because it always receives the instance object that is the implied subject of the method call. It’s usually called ``` self by convention.
Because method functions always have this implied subject ``` object context by default, we say they are “object-oriented”—i.e., designed to process or change objects. 5.
If the __init__ method is coded or inherited in a class, Python calls it automatically each time an instance of that class is created.
It’s known as the constructor method; it is passed the new instance implicitly, as well as any arguments passed explicitly to the class name.
It’s also the most commonly used operator overloading method. If no __init__ method is present, instances simply begin life as empty namespaces. 6.
You create a class instance by calling the class name as though it were a function; any arguments passed into the class name show up as arguments two and beyond in the __init__ constructor method.
The new instance remembers the class it was created from for inheritance purposes. 7.
You create a class by running a class statement; like function definitions, these statements normally run when the enclosing module file is imported (more on this in the next chapter). 8.
You specify a class’s superclasses by listing them in parentheses in the class statement, after the new class’s name.
The left-to-right order in which the classes are listed in the parentheses gives the left-to-right inheritance search order in the class tree. **|** ----- ----- ###### CHAPTER 26 ### Class Coding Basics Now that we’ve talked about OOP in the abstract, it’s time to see how this translates to actual code.
This chapter begins to fill in the syntax details behind the class model in Python. If you’ve never been exposed to OOP in the past, classes can seem somewhat complicated if taken in a single dose.
To make class coding easier to absorb, we’ll begin our detailed exploration of OOP by taking a first look at some basic classes in action in this chapter.
We’ll expand on the details introduced here in later chapters of this part of the book, but in their basic form, Python classes are easy to understand. In fact, classes have just three primary distinctions.
At a base level, they are mostly just namespaces, much like the modules we studied in Part V.
Unlike modules, though, classes also have support for generating multiple objects, for namespace inheritance, and for operator overloading.
Let’s begin our class statement tour by exploring each of these three distinctions in turn. ###### Classes Generate Multiple Instance Objects To understand how the multiple objects idea works, you have to first understand that there are two kinds of objects in Python’s OOP model: class objects and instance objects.
Class objects provide default behavior and serve as factories for instance objects. Instance objects are the real objects your programs process—each is a namespace in its own right, but inherits (i.e., has automatic access to) names in the class from which it was created.
Class objects come from statements, and instances come from calls; each time you call a class, you get a new instance of that class. ----- This object-generation concept is very different from any of the other program constructs we’ve seen so far in this book.
In effect, classes are essentially factories for generating multiple instances.
By contrast, only one copy of each module is ever imported into a single program (in fact, one reason that we have to call imp.reload is to update the single module object so that changes are reflected once they’ve been made). The following is a quick summary of the bare essentials of Python OOP.
As you’ll see, Python classes are in some ways similar to both defs and modules, but they may be quite different from what you’re used to in other languages. ###### Class Objects Provide Default Behavior When we run a class statement, we get a class object.
Here’s a rundown of the main properties of Python classes: - The `class` **statement creates a class object and assigns it a name.
Just like the** function `def statement, the Python` `class statement is an` _executable statement._ When reached and run, it generates a new class object and assigns it to the name in the class header.
Also, like defs, class statements typically run when the files they are coded in are first imported. - Assignments inside `class` **statements make class attributes.
Just like in module** files, top-level assignments within a class statement (not nested in a def) generate attributes in a class object.
Technically, the class statement scope morphs into the attribute namespace of the class object, just like a module’s global scope.
After running a `class statement, class attributes are accessed by name qualification:` ``` object.name. ``` - Class attributes provide object state and behavior.
Attributes of a class object record state information and behavior to be shared by all instances created from the class; function def statements nested inside a class generate methods, which process instances. ###### Instance Objects Are Concrete Items When we call a class object, we get an instance object.
Here’s an overview of the key points behind class instances: - Calling a class object like a function makes a new instance object.
Each time a class is called, it creates and returns a new instance object.
Instances represent concrete items in your program’s domain. - Each instance object inherits class attributes and gets its own namespace. Instance objects created from classes are new namespaces; they start out empty but inherit attributes that live in the class objects from which they were generated. **|** ----- ...
To begin, let’s define a class named FirstClass by running a Python class statement interactively: `>>> class FirstClass:` _# Define a class object_ `...
def setdata(self, value):` _# Define class methods_ `... self.data = value` _# self is the instance_ ``` ... def display(self): ``` `...
print(self.data)` _# self.data: per instance_ ``` ... ``` We’re working interactively here, but typically, such a statement would be run when the module file it is coded in is imported.
Like functions created with defs, this class won’t even exist until Python reaches and runs this statement. Like all compound statements, the class starts with a header line that lists the class name, followed by a body of one or more nested and (usually) indented statements. Here, the nested statements are defs; they...
Here, it assigns function objects to the names `setdata and` `display in the` `class statement’s scope, and so generates` attributes attached to the class: FirstClass.setdata and FirstClass.display.
In fact, any name assigned at the top level of the class’s nested block becomes an attribute of the class. Functions inside a class are usually called methods.
They’re coded with normal defs, and they support everything we’ve learned about functions already (they can have defaults, return values, and so on).
But in a method function, the first argument automatically receives an implied instance object when called—the subject of the call.
We need to create a couple of instances to see how this works: `>>> x = FirstClass()` _# Make two instances_ `>>> y = FirstClass()` _# Each is a new namespace_ By _calling the class this way (notice the parentheses), we generate instance objects,_ which are just namespaces that have access to their classes’ attribute...
Properly speaking, at this point, we have three objects: two instances and a class. Really, we have three linked namespaces, as sketched in Figure 26-1.
In OOP terms, we say that `x “is a”` ``` FirstClass, as is y. ``` **|** ----- _Figure 26-1. Classes and instances are linked namespace objects in a class tree that is searched by_ _inheritance.
Here, the “data” attribute is found in instances, but “setdata” and “display” are in the_ _class above them._ The two instances start out empty but have links back to the class from which they were generated.
If we qualify an instance with the name of an attribute that lives in the class object, Python fetches the name from the class by inheritance search (unless it also lives in the instance): `>>> x.setdata("King Arthur")` _# Call methods: self is x_ `>>> y.setdata(3.14159)` _# Runs: FirstClass.setdata(y, 3.14159)_ Neit...
And that’s about all there is to inheritance in Python: it happens at attribute qualification time, and it just involves looking up names in linked objects (e.g., by following the is-a links in Figure 26-1). In the `setdata function inside` `FirstClass, the value passed in is assigned to` ``` self.data.
Within a method, self—the name given to the leftmost argument by con ``` vention—automatically refers to the instance being processed (x or y), so the assignments store values in the instances’ namespaces, not the class’s (that’s how the data names in Figure 26-1 are created). Because classes can generate multiple ins...
When we call the class’s `display` method to print self.data, we see that it’s different in each instance; on the other hand, the name display itself is the same in x and y, as it comes (is inherited) from the class: `>>> x.display()` _# self.data differs in each instance_ ``` King Arthur >>> y.display() 3.14159...
As with everything else in Python, there are no declarations for instance attributes (sometimes called members); they spring into existence the first time they are assigned values, just like simple variables.
In fact, if we were to call ``` display on one of our instances before calling setdata, we would trigger an undefined ``` name error—the attribute named data doesn’t even exist in memory until it is assigned within the setdata method. **|** ----- As another way to appreciate how dynamic this model is, consider tha...
Classes usually create all of the instance’s attributes by assignment to the self argument, but they don’t have to; programs can fetch, change, or create attributes on any objects to which they have references. ###### Classes Are Customized by Inheritance Besides serving as factories for generating multiple instance ...
Instance objects generated from a class inherit the class’s attributes.
Python also allows classes to inherit from other classes, opening the door to coding hierarchies of classes that specialize behavior—by redefining attributes in subclasses that appear lower in the hierarchy, we override the more general definitions of those attributes higher in the tree.
In effect, the further down the hierarchy we go, the more specific the software becomes.
Here, too, there is no parallel with modules: their attributes live in a single, flat namespace that is not as amenable to customization. In Python, instances inherit from classes, and classes inherit from superclasses.
Here are the key ideas behind the machinery of attribute inheritance: - Superclasses are listed in parentheses in a `class` **header.
To inherit attributes** from another class, just list the class in parentheses in a class statement’s header. The class that inherits is usually called a subclass, and the class that is inherited from is its superclass. - Classes inherit attributes from their superclasses.
Just as instances inherit the attribute names defined in their classes, classes inherit all the attribute names defined in their superclasses; Python finds them automatically when they’re accessed, if they don’t exist in the subclasses. - Instances inherit attributes from all accessible classes.
Each instance gets names from the class it’s generated from, as well as all of that class’s superclasses. When looking for a name, Python checks the instance, then its class, then all superclasses. **|** ----- - Each `object.attribute` **reference invokes a new, independent search.
Python** performs an independent search of the class tree for each attribute fetch expression. This includes references to instances and classes made outside class statements (e.g., X.attr), as well as references to attributes of the self instance argument in class method functions.
Each `self.attr expression in a method invokes a new` search for attr in self and above. - Logic changes are made by subclassing, not by changing superclasses.
By redefining superclass names in subclasses lower in the hierarchy (class tree), subclasses replace and thus customize inherited behavior. The net effect, and the main purpose of all this searching, is that classes support factoring and customization of code better than any other language tool we’ve seen so far. On t...
First, we’ll define a new class, SecondClass, that inherits all of FirstClass’s names and provides one of its own: `>>> class SecondClass(FirstClass):` _# Inherits setdata_ `...
def display(self):` _# Changes display_ ``` ... print('Current value = "%s"' % self.data) ... SecondClass defines the display method to print with a different format.
By defining ``` an attribute with the same name as an attribute in FirstClass, SecondClass effectively replaces the display attribute in its superclass. Recall that inheritance searches proceed upward from instances, to subclasses, to superclasses, stopping at the first appearance of the attribute name that it finds.
In this case, since the `display name in` `SecondClass will be found before the one in` `First` `Class, we say that SecondClass` _overrides_ `FirstClass’s display.
Sometimes we call this` act of replacing attributes by redefining them lower in the tree overloading. The net effect here is that SecondClass specializes FirstClass by changing the behavior of the display method.
On the other hand, SecondClass (and any instances created from it) still inherits the setdata method in FirstClass verbatim.
Let’s make an instance to demonstrate: ``` >>> z = SecondClass() ``` `>>> z.setdata(42)` _# Finds setdata in FirstClass_ `>>> z.display()` _# Finds overridden method in SecondClass_ ``` Current value = "42" ``` **|** ----- As before, we make a SecondClass instance object by calling it.
The setdata call still runs the version in FirstClass, but this time the display attribute comes from Second ``` Class and prints a custom message.
Figure 26-2 sketches the namespaces involved. ``` _Figure 26-2. Specialization by overriding inherited names by redefining them in extensions lower in_ _the class tree.
Here, SecondClass redefines and so customizes the “display” method for its instances._ Now, here’s a very important thing to notice about OOP: the specialization introduced in SecondClass is completely external to FirstClass.
That is, it doesn’t affect existing or future FirstClass objects, like the x from the prior example: `>>> x.display()` _# x is still a FirstClass instance (old message)_ ``` New value ``` Rather than changing `FirstClass, we customized it.
Naturally, this is an artificial ex-` ample, but as a rule, because inheritance allows us to make changes like this in external components (i.e., in subclasses), classes often support extension and reuse better than functions or modules can. ###### Classes Are Attributes in Modules Before we move on, remember that th...
It’s just a variable assigned to an object when the class statement runs, and the object can be referenced with any normal expression.
For instance, if our FirstClass was coded in a module file instead of being typed interactively, we could import it and use its name normally in a class header line: ``` from modulename import FirstClass # Copy name into my scope class SecondClass(FirstClass): # Use class name directly def display(se...
For example, more than one class can be coded in a single module file—like other statements in a module, class statements are run during imports to define names, and these names become distinct module attributes.
More generally, each module may arbitrarily mix any number of variables, functions, and classes, and all names in a module behave the same way.
The file food.py demonstrates: _# food.py_ ``` var = 1 # food.var def func(): # food.func ... class spam: # food.spam ... class ham: # food.ham ... class eggs: # food.eggs ... ``` This holds true even if t...