Text stringlengths 1 9.41k |
|---|
Moreover, Python 3.0 extends this model by also allowing simple_
functions in a class to serve the role of static methods without extra protocol, when
called through a class.
_Instance methods are the normal (and default) case that we’ve seen in this book. |
An_
instance method must always be called with an instance object. |
When you call it
through an instance, Python passes the instance to the first (leftmost) argument automatically; when you call it through a class, you must pass along the instance manually
(for simplicity, I’ve omitted some class imports in interactive sessions like this one):
`>>> obj = Methods()` _# Make an instance... |
Unlike simple_
functions outside a class, their names are local to the scopes of the classes in which they
are defined, and they may be looked up by inheritance. |
Instance-less functions can be
called through a class normally in Python 3.0, but never by default in 2.6. |
Using the
```
staticmethod built-in allows such methods to also be called through an instance in 3.0
```
and through both a class and an instance in Python 2.6 (the first of these works in 3.0
without staticmethod, but the second does not):
`>>> Methods.smeth(3)` _# Static method, call through class_
```
3 ... |
The following subclass
and new testing session illustrate:
```
class Sub(Spam):
def printNumInstances(): # Override a static method
print("Extra stuff...") # But call back to original
Spam.printNumInstances()
printNumInstances = staticmethod(printNumInstances)
>>> a = Sub()
>>> b... |
Rather than hardcoding the class
name, the class method uses the automatically passed class object generically:
```
class Spam:
numInstances = 0 # Use class method instead of static
def __init__(self):
Spam.numInstances += 1
def printNumInstances(cls):
print("Number of instances:",... |
This has some subtle implications when trying
to update class data through the passed-in class. |
For example, if in module test.py we
subclass to customize as before, augment Spam.printNumInstances to also display its
```
cls argument, and start a new testing session:
class Spam:
numInstances = 0 # Trace class passed in
def __init__(self):
Spam.numInstances += 1
def printNumInstance... |
<class 'test.Sub'>
Number of instances: 2 <class 'test.Spam'>
```
**|**
-----
`>>> Sub.printNumInstances()` _# Call from subclass itself_
```
Extra stuff... |
<class 'test.Sub'>
Number of instances: 2 <class 'test.Spam'>
>>> y.printNumInstances()
Number of instances: 2 <class 'test.Spam'>
```
In the first call here, a class method call is made through an instance of the Sub subclass,
and Python passes the lowest class, Sub, to the class method. |
All is well in this case—
since Sub’s redefinition of the method calls the Spam superclass’s version explicitly, the
superclass method in Spam receives itself in its first argument. |
But watch what happens
for an object that simply inherits the class method:
```
>>> z = Other()
>>> z.printNumInstances()
Number of instances: 3 <class 'test.Other'>
```
This last call here passes `Other to` `Spam’s class method. |
This works in this example`
because _fetching the counter finds it in_ `Spam by inheritance. If this method tried to`
_assign to the passed class’s data, though, it would update_ `Object, not` `Spam! |
In this`
specific case, Spam is probably better off hardcoding its own class name to update its
data, rather than relying on the passed-in class argument.
###### Counting instances per class with class methods
In fact, because class methods always receive the lowest class in an instance’s tree:
- Static methods and... |
In the following, the top-level superclass uses a class method
to manage state information that varies for and is stored on each class in the tree—
similar in spirit to the way instance methods manage state information in class
instances:
```
class Spam:
numInstances = 0
def count(cls): # Per-class i... |
In recent Python versions, though, the static
and class method designations have become even simpler with the advent of function
decoration syntax—a way to apply one function to another that has roles well beyond
the static method use case that was its motivation. |
This syntax also allows us to augment
classes in Python 2.6 and 3.0—to initialize data like the numInstances counter in the
last example, for instance. |
The next section explains how.
###### Decorators and Metaclasses: Part 1
Because the staticmethod call technique described in the prior section initially seemed
obscure to some users, a feature was eventually added to make the operation simpler.
_Function decorators provide a way to specify special operation modes fo... |
For instance, they may be used
to augment functions with code that logs calls made to them, checks the types of passed
arguments during debugging, and so on. |
In some ways, function decorators are similar
to the delegation design pattern we explored in Chapter 30, but they are designed to
augment a specific function or method call, not an entire object interface.
Python provides some built-in function decorators for operations such as marking static
methods, but programmers... |
Although
they are not strictly tied to classes, user-defined function decorators often are coded as
classes to save the original functions, along with other data, as state information.
There’s also a more recent related extension available in Python 2.6 and 3.0: class dec_orators are directly tied to the class model, a... |
A function decorator is coded on a line by itself just before the def statement that defines a function or method. |
It consists of the @ symbol, followed by what
we call a _metafunction—a function (or other callable object) that manages another_
function. |
Static methods today, for example, may be coded with decorator syntax like
this:
**|**
-----
```
class C:
@staticmethod # Decoration syntax
def meth():
...
```
Internally, this syntax has the same effect as the following (passing the function through
the decorator and assigning the ... |
The net effect is that
calling the method function’s name later actually triggers the result of its
```
staticmethod decorator first. |
Because a decorator can return any sort of object, this
```
allows the decorator to insert a layer of logic to be run on every call. |
The decorator
function is free to return either the original function itself, or a new object that saves
the original function passed to the decorator to be invoked indirectly after the extra
logic layer runs.
With this addition, here’s a better way to code our static method example from the
prior section in either Py... |
In fact, any
such function can be used in this way—even user-defined functions we code ourselves,
as the next section explains.
###### A First Function Decorator Example
Although Python provides a handful of built-in functions that can be used as decorators,
we can also write custom decorators of our own. |
Because of their wide utility, we’re
going to devote an entire chapter to coding decorators in the next part of this book. |
As
a quick example, though, let’s look at a simple user-defined decorator at work.
**|**
-----
Recall from Chapter 29 that the __call__ operator overloading method implements a
function-call interface for class instances. |
The following code uses this to define a class
that saves the decorated function in the instance and catches calls to the original name.
Because this is a class, it also has state information (a counter of calls made):
```
class tracer:
def __init__(self, func):
self.calls = 0
self.func = func
def... |
This method
```
counts and logs the call, and then dispatches it to the original wrapped function. |
Note
how the *name argument syntax is used to pack and unpack the passed-in arguments;
because of this, this decorator can be used to wrap any function with any number of
positional arguments.
The net effect, again, is to add a layer of logic to the original spam function. |
Here is the
script’s output—the first line comes from the tracer class, and the second comes from
the spam function:
```
call 1 to spam
1 2 3
call 2 to spam
a b c
call 3 to spam
4 5 6
```
Trace through this example’s code for more insight. |
As it is, this decorator works for
any function that takes positional arguments, but it does not return the decorated
function’s _result, doesn’t handle_ _keyword arguments, and cannot decorate class_
_method functions (in short, for methods its __call__ would be passed a tracer instance_
only). |
As we’ll see in Part VIII, there are a variety of ways to code function decorators,
including nested def statements; some of the alternatives are better suited to methods
than the version shown here.
**|**
-----
###### Class Decorators and Metaclasses
Function decorators turned out to be so useful that Python 2.6 ... |
In short, class
_decorators are similar to function decorators, but they are run at the end of a_ `class`
statement to rebind a class name to a callable. |
As such, they can be used to either
manage classes just after they are created, or insert a layer of wrapper logic to manage
instances when they are later created. |
Symbolically, the code structure:
```
def decorator(aClass): ...
@decorator
class C: ...
```
is mapped to the following equivalent:
```
def decorator(aClass): ...
class C: ...
C = decorator(C)
```
The class decorator is free to augment the class itself, or return an object that intercepts
later instance c... |
For instance, in the example in the section “Counting
instances per class with class methods” on page 803, we could use this hook to automatically augment the classes with instance counters and any other data required:
```
def count(aClass):
aClass.numInstances = 0
return aClass # Return class itself,... |
# Same as Spam = count(Spam)
@count
class Sub(Spam): ... |
# numInstances = 0 not needed here
@count
class Other(Spam): ...
```
_Metaclasses are a similarly advanced class-based tool whose roles often intersect with_
those of class decorators. |
They provide an alternate model, which routes the creation
of a class object to a subclass of the top-level type class, at the conclusion of a class
statement:
```
class Meta(type):
def __new__(meta, classname, supers, classdict): ...
class C(metaclass=Meta): ...
```
**|**
-----
In Python 2.6, the effect is... |
The net
effect, as with class decorators, is to define code to be run automatically at class creation
time. |
Both schemes are free to augment a class or return an arbitrary object to replace
it—a protocol with almost limitless class-based possibilities.
###### For More Details
Naturally, there’s much more to the decorator and metaclass stories than I’ve shown
here. |
Although they are a general mechanism, decorators and metaclasses are advanced
features of interest primarily to tool writers, not application programmers, so we’ll defer
additional coverage until the final part of this book:
- Chapter 37 shows how to code properties using function decorator syntax.
- Chapter 38 ha... |
Some of the topics we’ll cover
in this section are more like case studies of advanced class usage than real problems,
and one or two of these gotchas have been eased by recent Python releases.
###### Changing Class Attributes Can Have Side Effects
Theoretically speaking, classes (and class instances) are mutable obje... |
Like built-in
lists and dictionaries, they can be changed in-place by assigning to their attributes—
and as with lists and dictionaries, this means that changing a class or instance object
may impact multiple references to it.
**|**
-----
That’s usually what we want (and is how objects change their state in general... |
Because all instances generated from a class share the class’s namespace, any changes at
the class level are reflected in all instances, unless they have their own versions of the
changed class attributes.
Because classes, modules, and instances are all just objects with attribute namespaces,
you can normally change t... |
Consider the following class. |
Inside the class body, the assignment to the name a generates an attribute
```
X.a, which lives in the class object at runtime and will be inherited by all of X’s instances:
>>> class X:
```
`... |
a = 1` _# Class attribute_
```
...
>>> I = X()
```
`>>> I.a` _# Inherited by instance_
```
1
>>> X.a
1
```
So far, so good—this is the normal case. |
But notice what happens when we change the
class attribute dynamically outside the class statement: it also changes the attribute in
every object that inherits from the class. |
Moreover, new instances created from the class
during this session or program run also get the dynamically set value, regardless of what
the class’s source code says:
`>>> X.a = 2` _# May change more than X_
`>>> I.a` _# I changes too_
```
2
```
`>>> J = X()` _# J inherits from X's runtime values_
`>>> J.a` _# (but... |
You be the judge. |
As we learned in Chapter 26, you can actually get work done by changing class attributes without ever making
a single instance; this technique can simulate the use of “records” or “structs” in other
languages. |
As a refresher, consider the following unusual but legal Python program:
```
class X: pass # Make a few attribute namespaces
class Y: pass
X.a = 1 # Use class attributes as variables
X.b = 2 # No instances anywhere to be found
X.c = 3
Y.a = X.a + X.b + X.c
for X.i in... |
This is a perfectly legal Python programming trick, but it’s less
appropriate when applied to classes written by others; you can’t always be sure that
class attributes you change aren’t critical to the class’s internal behavior. |
If you’re out
**|**
-----
to simulate a C struct, you may be better off changing instances than classes, as that
way only one object is affected:
```
class Record: pass
X = Record()
X.name = 'bob'
X.job = 'Pizza maker'
###### Changing Mutable Class Attributes Can Have Side Effects, Too
```
This gotcha is ... |
Because class attributes are shared by all
instances, if a class attribute references a mutable object, changing that object in-place
from any instance impacts all instances at once:
```
>>> class C:
```
`... |
shared = []` _# Class attribute_
```
... def __init__(self):
```
`... |
self.perobj = []` _# Instance attribute_
```
...
```
`>>> x = C()` _# Two instances_
`>>> y = C()` _# Implicitly share class attrs_
```
>>> y.shared, y.perobj
([], [])
```
`>>> x.shared.append('spam')` _# Impacts y's view too!_
`>>> x.perobj.append('spam')` _# Impacts x's data only_
```
>>> x.shared, x.perobj... |
All of these are cases of general behavior—multiple references to
a mutable object—and all are impacted if the shared object is changed in-place from
any reference. |
Here, this occurs in class attributes shared by all instances via inheritance, but it’s the same phenomenon at work. |
It may be made more subtle by the
different behavior of assignments to instance attributes themselves:
```
x.shared.append('spam') # Changes shared object attached to class in-place
x.shared = 'spam' # Changed or creates instance attribute attached to x
```
but again, this is not a problem, it’s just somethin... |
Python always searches superclasses from left to right, according to their order
in the header line.
For instance, in the multiple inheritance example we studied in Chapter 30, suppose
that the Super class implemented a __str__ method, too:
```
class ListTree:
def __str__(self): ...
class Super:
def __str_... |
As inheritance searches proceed from left to right, we would get the method from whichever class is listed first
(leftmost) in Sub’s class header. |
Presumably, we would list ListTree first because its
whole purpose is its custom __str__ (indeed, we had to do this in Chapter 30 when
mixing this class with a tkinter.Button that had a __str__ of its own).
But now suppose Super and ListTree have their own versions of other same-named
attributes, too. |
If we want one name from Super and another from ListTree, the order
in which we list them in the class header won’t help—we will have to override inheritance by manually assigning to the attribute name in the Sub class:
```
class ListTree:
def __str__(self): ...
def other(self): ...
class Super:
def __s... |
Because it is lower in the tree, Sub.other effectively hides
```
ListTree.other, the attribute that the inheritance search would normally find. |
Simi
```
larly, if we listed Super first in the class header to pick up its other, we would need to
select ListTree’s method explicitly:
**|**
-----
```
class Sub(Super, ListTree): # Get Super's other by order
__str__ = Lister.__str__ # Explicitly pick Lister.__str__
```
Multiple inheritance is ... |
Even if you understood the last paragraph,
it’s still a good idea to use it sparingly and carefully. |
Otherwise, the meaning of a name
may come to depend on the order in which classes are mixed in an arbitrarily
far-removed subclass. |
(For another example of the technique shown here in action, see
the discussion of explicit conflict resolution in “The “New-Style” Class
Model” on page 777.)
As a rule of thumb, multiple inheritance works best when your mix-in classes are as
self-contained as possible—because they may be used in a variety of contexts,... |
The
pseudoprivate __X attributes feature we studied in Chapter 30 can help by localizing
names that a class relies on owning and limiting the names that your mix-in classes add
to the mix. |
In this example, for instance, if ListTree only means to export its custom
```
__str__, it can name its other method __other to avoid clashing with like-named classes
```
in the tree.
###### Methods, Classes, and Nested Scopes
This gotcha went away in Python 2.2 with the introduction of nested function scopes,
but I... |
Moreover, methods are further nested functions,
so the same issues apply. |
Confusion seems to be especially common when classes are
nested.
In the following example (the file nester.py), the generate function returns an instance
of the nested `Spam class. |
Within its code, the class name` `Spam is assigned in the`
```
generate function’s local scope. |
However, in versions of Python prior to 2.2, within the
```
class’s method function the class name Spam is not visible—method has access only to its
own local scope, the module surrounding generate, and built-in names:
```
def generate(): # Fails prior to Python 2.2, works later
class Spam:
count =... |
However, it doesn’t work before 2.2 (we’ll look at some possible
solutions momentarily).
Note that even in 2.2 and later, method defs cannot see the local scope of the enclosing
_class; they can only see the local scopes of enclosing defs. |
That’s why methods must_
go through the self instance or the class name to reference methods and other attributes
defined in the enclosing class statement. |
For example, code in the method must use
```
self.count or Spam.count, not just count.
```
If you’re using a release prior to 2.2, there are a variety of ways to get the preceding
example to work. |
One of the simplest is to move the name Spam out to the enclosing
module’s scope with a `global declaration. |
Because` `method sees global names in the`
enclosing module, references to Spam will work:
```
def generate():
global Spam # Force Spam to module scope
class Spam:
count = 1
def method(self):
print(Spam.count) # Works: in global (enclosing module)
return Spam()
generate().me... |
The nested `method function and the top-level` `generate will then find`
```
Spam in their global scopes:
def generate():
return Spam()
class Spam: # Define at top level of module
count = 1
def method(self):
print(Spam.count) # Works: in global (enclosing module)
generate().method()
... |
In Python 3.0 (and 2.6, when new-style
classes are used), the names of operator overloading methods implicitly fetched by
built-in operations are not routed through generic attribute-interception methods. |
The
```
__str__ method used by printing, for example, never invokes __getattr__. Instead,
```
Python 3.0 looks up such names in classes and skips the normal runtime instance
lookup mechanism entirely. |
To work around this, such methods must be redefined in
wrapper classes, either by hand, with tools, or by definition in superclasses. |
We’ll revisit
this gotcha in Chapters 37 and 38.
###### “Overwrapping-itis”
When used well, the code reuse features of OOP make it excel at cutting development
time. |
Sometimes, though, OOP’s abstraction potential can be abused to the point of
making code difficult to understand. |
If classes are layered too deeply, code can become
obscure; you may have to search through many classes to discover what an operation
does.
For example, I once worked in a C++ shop with thousands of classes (some machinegenerated), and up to 15 levels of inheritance. |
Deciphering method calls in such a
complex system was often a monumental task: multiple classes had to be consulted for
even the most basic of operations. |
In fact, the logic of the system was so deeply wrapped
that understanding a piece of code in some cases required days of wading through
related files.
The most general rule of thumb of Python programming applies here, too: don’t make
things complicated unless they truly must be. |
Wrapping your code in multiple layers
of classes to the point of incomprehensibility is always a bad idea. |
Abstraction is the
basis of polymorphism and encapsulation, and it can be a very effective tool when used
well. |
However, you’ll simplify debugging and aid maintainability if you make your class
interfaces intuitive, avoid making your code overly abstract, and keep your class hierarchies short and flat unless there is a good reason to do otherwise.
**|**
-----
###### Chapter Summary
This chapter presented a handful of advanc... |
Most of these are
optional extensions to the OOP model in Python, but they may become more useful
as you start writing larger object-oriented programs. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.