Text stringlengths 1 9.41k |
|---|
Generic tools can avoid hardcoded solutions that must be kept in sync with the
rest of the class as it evolves over time. |
A generic __str__ print method, for example,
need not be updated each time a new attribute is added to instances in an
```
__init__ constructor. |
In addition, a generic print method inherited by all classes
```
only appears, and need only be modified, in one place—changes in the generic
version are picked up by all classes that inherit from the generic class. |
Again, eliminating code redundancy cuts future development effort; that’s one of the primary
assets classes bring to the table.
7. |
Inheritance is best at coding extensions based on direct customization (like our
```
Manager specialization of Person). |
Composition is well suited to scenarios where
```
multiple objects are aggregated into a whole and directed by a controller layer class.
Inheritance passes calls up to reuse, and composition passes down to delegate.
Inheritance and composition are not mutually exclusive; often, the objects embedded in a controller are... |
The classes in this chapter could be used as boilerplate “template” code to
implement a variety of types of databases. |
Essentially, you can repurpose them by
modifying the constructors to record different attributes and providing whatever
methods are appropriate for the target application. |
For instance, you might use
attributes such as name, address, birthday, phone, email, and so on for a contacts
database, and methods appropriate for this purpose. |
A method named sendmail,
for example, might use Python’s standard library smptlib module to send an email
to one of the contacts automatically when called (see Python’s manuals or application-level books for more details on such tools). |
The AttrDisplay tool we wrote
here could be used verbatim to print your objects, because it is intentionally generic. |
Most of the shelve database code here can be used to store your objects, too,
with minor changes.
**|**
-----
-----
###### CHAPTER 28
### Class Coding Details
If you haven’t quite gotten all of Python OOP yet, don’t worry; now that we’ve had a
quick tour, we’re going to dig a bit deeper and study the concepts int... |
In this and the following chapter, we’ll take another look at class mechanics. |
Here, we’re going to study classes, methods, and inheritance, formalizing and
expanding on some of the coding ideas introduced in Chapter 26. |
Because the class is
our last namespace tool, we’ll summarize Python’s namespace concepts here as well.
The next chapter continues this in-depth second pass over class mechanics by covering
one specific aspect: operator overloading. |
Besides presenting the details, this chapter
and the next also give us an opportunity to explore some larger classes than those we
have studied so far.
###### The class Statement
Although the Python class statement may seem similar to tools in other OOP languages
on the surface, on closer inspection, it is quite diff... |
For example, as in C++, the class statement is Python’s main OOP tool,
but unlike in C++, Python’s class is not a declaration. |
Like a def, a class statement is
an object builder, and an implicit assignment—when run, it generates a class object
and stores a reference to it in the name used in the header. |
Also like a `def, a class`
statement is true executable code—your class doesn’t exist until Python reaches and
runs the class statement that defines it (typically while importing the module it is coded
in, but not before).
###### General Form
```
class is a compound statement, with a body of indented statements typica... |
In the header, superclasses are listed in parentheses after the class
name, separated by commas. |
Listing more than one superclass leads to multiple inheritance (which we’ll discuss more formally in Chapter 30). |
Here is the statement’s
general form:
-----
```
class <name>(superclass,...): # Assign to name
data = value # Shared class data
def method(self,...): # Methods
self.member = value # Per-instance data
```
Within the class statement, any assignments generate class attributes, ... |
So, how do you get from the
```
class statement to a namespace?
```
Here’s how. Just like in a module file, the statements nested in a class statement body
create its attributes. |
When Python executes a class statement (not a call to a class), it
runs all the statements in its body, from top to bottom. |
Assignments that happen during
this process create names in the class’s local scope, which become attributes in the
associated class object. |
Because of this, classes resemble both modules and functions:
- Like functions, class statements are local scopes where names created by nested
assignments live.
- Like names in a module, names assigned in a class statement become attributes
in a class object.
The main distinction for classes is that their namespa... |
All the statements inside the class statement run
when the `class statement itself runs (not when the class is later called to make an`
instance). |
Assigning names inside the `class statement makes class attributes, and`
nested defs make class methods, but other assignments make attributes, too.
For example, assignments of simple nonfunction objects to class attributes produce
_data attributes, shared by all instances:_
```
>>> class SharedData:
```
`... |
spam = 42` _# Generates a class data attribute_
```
...
```
`>>> x = SharedData()` _# Make two instances_
```
>>> y = SharedData()
```
`>>> x.spam, y.spam` _# They inherit and share 'spam'_
```
(42, 42)
```
**|**
-----
Here, because the name `spam is assigned at the top level of a` `class statement, it is`
... |
We can change it by going
through the class name, and we can refer to it through either instances or the class.[*]
```
>>> SharedData.spam = 99
>>> x.spam, y.spam, SharedData.spam
(99, 99, 99)
```
Such class attributes can be used to manage information that spans all the instances—
a counter of the number of ins... |
Now, watch what happens if we assign the name `spam`
through an instance instead of the class:
```
>>> x.spam = 88
>>> x.spam, y.spam, SharedData.spam
(88, 99, 99)
```
Assignments to instance attributes create or change the names in the instance, rather
than in the shared class. |
More generally, inheritance searches occur only on attribute
_references, not on assignment: assigning to an object’s attribute always changes that_
object, and no other.[†] For example, y.spam is looked up in the class by inheritance, but
the assignment to x.spam attaches a name to x itself.
Here’s a more comprehensi... |
Suppose we run the following class:
```
class MixedNames: # Define class
data = 'spam' # Assign class attr
def __init__(self, value): # Assign method name
self.data = value # Assign instance attr
def display(self):
print(self.data, MixedNames.data) # ... |
It also
contains an = assignment statement; because this assignment assigns the name data
inside the class, it lives in the class’s local scope and becomes an attribute of the class
object. |
Like all class attributes, this data is inherited and shared by all instances of the
class that don’t have data attributes of their own.
When we make instances of this class, the name data is attached to those instances by
the assignment to self.data in the constructor method:
`>>> x = MixedNames(1)` _# Make two inst... |
In Python, it’s nothing special: all class attributes are
just names assigned in the class statement, whether they happen to reference functions (C++’s “methods”)
or something else (C++’s “members”). |
In Chapter 31, we’ll also meet Python static methods (akin to those
in C++), which are just self-less functions that usually process class attributes.
† Unless the class has redefined the attribute assignment operation to do something unique with the
```
__setattr__ operator overloading method (discussed in Chapter 2... |
The class’s display method prints both
versions, by first qualifying the self instance, and then the class.
By using these techniques to store attributes in different objects, we determine their
scope of visibility. |
When attached to classes, names are shared; in instances, names
record per-instance data, not shared behavior or data. |
Although inheritance searches
look up names for us, we can always get to an attribute anywhere in a tree by accessing
the desired object directly.
In the preceding example, for instance, specifying x.data or self.data will return an
instance name, which normally hides the same name in the class; however, `Mixed`
```
N... |
We’ll see various roles for such coding pat
```
terns later; the next section describes one of the most common.
###### Methods
Because you already know about functions, you also know about methods in classes.
Methods are just function objects created by def statements nested in a class statement’s body. |
From an abstract perspective, methods provide behavior for instance
objects to inherit. |
From a programming perspective, methods work in exactly the same
way as simple functions, with one crucial exception: a method’s first argument always
receives the instance object that is the implied subject of the method call.
In other words, Python automatically maps instance method calls to class method
functions a... |
Method calls made through an instance, like this:
```
instance.method(args...)
```
are automatically translated to class method function calls of this form:
```
class.method(instance, args...)
```
where the class is determined by locating the method name using Python’s inheritance
search procedure. |
In fact, both call forms are valid in Python.
Besides the normal inheritance of method attribute names, the special first argument
is the only real magic behind method calls. |
In a class method, the first argument is
usually called self by convention (technically, only its position is significant, not its
name). |
This argument provides methods with a hook back to the instance that is the
subject of the call—because classes generate many instance objects, they need to use
this argument to manage data that varies per instance.
**|**
-----
C++ programmers may recognize Python’s self argument as being similar to C++’s
```
this ... |
In Python, though, self is always explicit in your code: methods must
```
always go through self to fetch or change attributes of the instance being processed
by the current method call. |
This explicit nature of self is by design—the presence of
this name makes it obvious that you are using instance attribute names in your script,
not names in the local or global scope.
###### Method Example
To clarify these concepts, let’s turn to an example. |
Suppose we define the following
class:
```
class NextClass: # Define class
def printer(self, text): # Define method
self.message = text # Change instance
print(self.message) # Access instance
```
The name printer references a function object; because it’s assigned ... |
Normally, because methods like `printer are designed to process in-`
stances, we call them through instances:
`>>> x = NextClass()` _# Make instance_
`>>> x.printer('instance call')` _# Call its method_
```
instance call
```
`>>> x.message` _# Instance changed_
```
'instance call'
```
When we call the method by... |
Notice that
because Python automatically passes the first argument to self for us, we only actually
have to pass in one argument. |
Inside printer, the name self is used to access or set
per-instance data because it refers back to the instance currently being processed.
Methods may be called in one of two ways—through an instance, or through the class
itself. |
For example, we can also call printer by going through the class name, provided
we pass an instance to the self argument explicitly:
`>>> NextClass.printer(x, 'class call')` _# Direct class call_
```
class call
```
`>>> x.message` _# Instance changed again_
```
'class call'
```
**|**
-----
Calls routed throug... |
By default, in fact, you get
an error message if you try to call a method without any instance:
```
>>> NextClass.printer('bad call')
TypeError: unbound method printer() must be called with NextClass instance...
###### Calling Superclass Constructors
```
Methods are normally called through instances. |
Calls to methods through a class,
though, do show up in a variety of special roles. One common scenario involves the
constructor method. |
The __init__ method, like all attributes, is looked up by inheritance. This means that at construction time, Python locates and calls just one
```
__init__. |
If subclass constructors need to guarantee that superclass construction-time
```
logic runs, too, they generally must call the superclass’s `__init__ method explicitly`
through the class:
```
class Super:
def __init__(self, x):
...default code...
class Sub(Super):
def __init__(self, x, y):
Supe... |
Naturally, you should only call the superclass constructor this
way if you really want it to run—without the call, the subclass replaces it completely.
For a more realistic illustration of this technique in action, see the Manager class example
in the prior chapter’s tutorial.[‡]
###### Other Method Call Possibilities... |
In Chapter 31, we’ll also meet a
new option added in Python 2.2, static methods, that allow you to code methods that
do not expect instance objects in their first arguments. |
Such methods can act like simple
instanceless functions, with names that are local to the classes in which they are coded,
and may be used to manage class data. |
A related concept, the class method, receives a
class when called instead of an instance and can be used to manage per-class data. |
These
are advanced and optional extensions, though; normally, you must always pass an
instance to a method, whether it is called through an instance or a class.
‡ On a somewhat related note, you can also code multiple __init__ methods within the same class, but only
the last definition will be used; see Chapter 30 for... |
This section expands on some of the mechanisms and roles of attribute inheritance in Python.
In Python, inheritance happens when an object is qualified, and it involves searching
an attribute definition tree (one or more namespaces). |
Every time you use an expression
of the form object.attr (where object is an instance or class object), Python searches
the namespace tree from bottom to top, beginning with object, looking for the first
```
attr it can find. |
This includes references to self attributes in your methods. |
Because
```
lower definitions in the tree override higher ones, inheritance forms the basis of
specialization.
###### Attribute Tree Construction
Figure 28-1 summarizes the way namespace trees are constructed and populated with
names. |
Generally:
- Instance attributes are generated by assignments to self attributes in methods.
- Class attributes are created by statements (assignments) in class statements.
- Superclass links are made by listing classes in parentheses in a `class statement`
header.
The net result is a tree of attribute namespace... |
Python searches
upward in this tree, from instances to superclasses, each time you use qualification to
fetch an attribute name from an instance object.[§]
###### Specializing Inherited Methods
The tree-searching model of inheritance just described turns out to be a great way to
specialize systems. |
Because inheritance finds names in subclasses before it checks superclasses, subclasses can replace default behavior by redefining their superclasses’
attributes. |
In fact, you can build entire systems as hierarchies of classes, which are
extended by adding new external subclasses rather than changing existing logic
in-place.
§ This description isn’t 100% complete, because we can also create instance and class attributes by assigning
to objects outside `class statements—but that... |
In Python, all attributes are always accessible by`
default. |
We’ll talk more about attribute name privacy in Chapter 29 when we study `__setattr__, in`
Chapter 30 when we meet `__X names, and again in` Chapter 38, where we’ll implement it with a class
decorator.
**|**
-----
The idea of redefining inherited names leads to a variety of specialization techniques.
For instance, ... |
We’ve already seen replacement in action.
Here’s an example that shows how extension works:
```
>>> class Super:
... def method(self):
... |
print('in Super.method')
...
>>> class Sub(Super):
```
`... def method(self):` _# Override method_
`... print('starting Sub.method')` _# Add actions here_
`... |
Super.method(self)` _# Run default action_
```
... print('ending Sub.method')
...
```
_Figure 28-1. |
Program code creates a tree of objects in memory to be searched by attribute inheritance._
_Calling a class creates a new instance that remembers its class, running a class statement creates a_
_new class, and superclasses are listed in parentheses in the class statement header. |
Each attribute_
_reference triggers a new bottom-up tree search—even references to self attributes within a class’s_
_methods._
Direct superclass method calls are the crux of the matter here. |
The Sub class replaces
```
Super’s method function with its own specialized version, but within the replacement,
Sub calls back to the version exported by Super to carry out the default behavior. |
In
```
other words, Sub.method just extends Super.method’s behavior, rather than replacing it
completely:
**|**
-----
`>>> x = Super()` _# Make a Super instance_
`>>> x.method()` _# Runs Super.method_
```
in Super.method
```
`>>> x = Sub()` _# Make a Sub instance_
`>>> x.method()` _# Runs Sub.method, calls Supe... |
The file shown in this section,
_specialize.py, defines multiple classes that illustrate a variety of common techniques:_
```
Super
```
Defines a method function and a delegate that expects an action in a subclass.
```
Inheritor
```
Doesn’t provide any new names, so it gets everything defined in Super.
```
Replacer
... |
Here’s the file:
```
class Super:
def method(self):
print('in Super.method') # Default behavior
def delegate(self):
self.action() # Expected to be defined
class Inheritor(Super): # Inherit method verbatim
pass
class Replacer(Super): # Replace method comple... |
First, the self-test code at the end of this
example creates instances of three different classes in a for loop. |
Because classes are
objects, you can put them in a tuple and create instances generically (more on this idea
later). |
Classes also have the special __name__ attribute, like modules; it’s preset to a
string containing the name in the class header. |
Here’s what happens when we run the
file:
```
% python specialize.py
Inheritor...
in Super.method
Replacer...
in Replacer.method
Extender...
starting Extender.method
in Super.method
ending Extender.method
Provider...
in Provider.action
###### Abstract Superclasses
```
Notice how the `Provider cl... |
When we call the`
```
delegate method through a Provider instance, two independent inheritance searches
```
occur:
1. |
On the initial `x.delegate call, Python finds the` `delegate method in` `Super by`
searching the `Provider instance and above. The instance` `x is passed into the`
method’s self argument as usual.
2. |
Inside the `Super.delegate method,` `self.action invokes a new, independent in-`
heritance search of self and above. |
Because self references a Provider instance,
the action method is located in the Provider subclass.
This “filling in the blanks” sort of coding structure is typical of OOP frameworks. |
At
least in terms of the delegate method, the superclass in this example is what is sometimes called an _abstract superclass—a class that expects parts of its behavior to be_
**|**
-----
provided by its subclasses. |
If an expected method is not defined in a subclass, Python
raises an undefined name exception when the inheritance search fails.
Class coders sometimes make such subclass requirements more obvious with assert
statements, or by raising the built-in NotImplementedError exception with raise statements (we’ll study statem... |
As a quick preview, here’s the assert scheme in action:
```
class Super:
def delegate(self):
self.action()
def action(self):
assert False, 'action must be defined!' # If this version is called
>>> X = Super()
>>> X.delegate()
AssertionError: action must be defined!
```
We’ll meet `assert ... |
Here, the expression
is always false so as to trigger an error message if a method is not redefined, and inheritance locates the version here. |
Alternatively, some classes simply raise a
```
NotImplementedError exception directly in such method stubs to signal the mistake:
class Super:
def delegate(self):
self.action()
def action(self):
raise NotImplementedError('action must be defined!')
>>> X = Super()
>>> X.delegate()
NotImplemen... |
def action(self): print('spam')
...
>>> X = Sub()
>>> X.delegate()
spam
```
For a somewhat more realistic example of this section’s concepts in action, see the “Zoo
animal hierarchy” exercise (exercise 8) at the end of Chapter 31, and its solution in
“Part VI, Classes and OOP” on page 1122 in Appendix B. |
Such taxonomies are a
**|**
-----
traditional way to introduce OOP, but they’re a bit removed from most developers’ job
descriptions.
###### Python 2.6 and 3.0 Abstract Superclasses
As of Python 2.6 and 3.0, the prior section’s abstract superclasses (a.k.a. |
“abstract base
classes”), which require methods to be filled in by subclasses, may also be implemented
with special class syntax. |
The way we code this varies slightly depending on the version.
In Python 3.0, we use a keyword argument in a `class header, along with special` `@`
decorator syntax, both of which we’ll study in detail later in this book:
```
from abc import ABCMeta, abstractmethod
class Super(metaclass=ABCMeta):
@abstractmetho... |
In 3.0, for example, here is the special syntax equivalent
of the prior section’s example:
```
>>> from abc import ABCMeta, abstractmethod
>>>
>>> class Super(metaclass=ABCMeta):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.