Text stringlengths 1 9.41k |
|---|
def normal(self, arg1, arg2):` _# Instance expected when called_
```
... |
return self.data + arg1 + arg2
...
>>> X = Selfless(2)
```
`>>> X.normal(3, 4)` _# Instance passed to self automatically_
```
9
```
`>>> Selfless.normal(X, 3, 4)` _# self expected by method: pass manually_
```
9
```
`>>> Selfless.selfless(3, 4)` _# No instance: works in 3.0, fails in 2.6!_
```
7
```
The l... |
Although this removes some potential error trapping in 3.0
(what if a programmer accidentally forgets to pass an instance?), it allows class methods
to be used as simple functions as long as they are not passed and do not expect a “self”
instance argument.
The following two calls still fail in both 3.0 and 2.6, though... |
In 2.6, such calls are errors unless an instance
is passed manually (more on static methods in the next chapter).
It’s important to be aware of the differences in behavior in 3.0, but bound methods are
generally more important from a practical perspective anyway. |
Because they pair together the instance and function in a single object, they can be treated as callables
generically. |
The next section demonstrates what this means in code.
For a more visual illustration of unbound method treatment in Python
3.0 and 2.6, see also the lister.py example in the multiple inheritance
section later in this chapter. |
Its classes print the value of methods fetched
from both instances and classes, in both versions of Python.
**|**
-----
###### Bound Methods and Other Callable Objects
As mentioned earlier, bound methods can be processed as generic objects, just like
simple functions—they can be passed around a program arbitrarily... |
Moreover, because
bound methods combine both a function and an instance in a single package, they can
be treated like any other callable object and require no special syntax when invoked.
The following, for example, stores four bound method objects in a list and calls them
later with normal call expressions:
```
>>> ... |
def __init__(self, base):
... self.base = base
... def double(self):
... return self.base * 2
... def triple(self):
... |
return self.base * 3
...
```
`>>> x = Number(2)` _# Class instance objects_
`>>> y = Number(3)` _# State + methods_
```
>>> z = Number(4)
```
`>>> x.double()` _# Normal immediate calls_
```
4
```
`>>> acts = [x.double, y.double, y.triple, z.double]` _# List of bound methods_
`>>> for act in acts:` _# Calls are... |
print(act())` _# Call as though functions_
```
...
4
6
9
8
```
Like simple functions, bound method objects have introspection information of their
own, including attributes that give access to the instance object and method function
they pair. |
Calling the bound method simply dispatches the pair:
```
>>> bound = x.double
>>> bound.__self__, bound.__func__
(<__main__.Number object at 0x0278F610>, <function double at 0x027A4ED0>)
>>> bound.__self__.base
2
```
`>>> bound()` _# Calls bound.__func__(bound.__self__, ...)_
```
4
```
In fact, bound meth... |
As
the following demonstrates, simple functions coded with a def or lambda, instances that
inherit a __call__, and bound instance methods can all be treated and called the same
way:
```
>>> def square(arg):
```
`... |
return arg ** 2` _# Simple functions (def or lambda)_
```
...
>>> class Sum:
```
`... def __init__(self, val):` _# Callable instances_
**|**
-----
```
... self.val = val
... |
def __call__(self, arg):
... return self.val + arg
...
>>> class Product:
```
`... def __init__(self, val):` _# Bound methods_
```
... self.val = val
... def method(self, arg):
... |
return self.val * arg
...
>>> sobject = Sum(2)
>>> pobject = Product(3)
```
`>>> actions = [square, sobject, pobject.method]` _# Function, instance, method_
`>>> for act in actions:` _# All 3 called same way_
`... |
print(act(5))` _# Call any 1-arg callable_
```
...
25
7
15
```
`>>> actions[-1](5)` _# Index, comprehensions, maps_
```
15
>>> [act(5) for act in actions]
[25, 7, 15]
>>> list(map(lambda act: act(5), actions))
[25, 7, 15]
```
Technically speaking, classes belong in the callable objects category too,... |
def __init__(self, val):` _# Classes are callables too_
`... self.val = -val` _# But called for object, not work_
`... def __repr__(self):` _# Instance print format_
```
... |
return str(self.val)
...
```
`>>> actions = [square, sobject, pobject.method, Negate]` _# Call a class too_
```
>>> for act in actions:
... |
print(act(5))
...
25
7
15
-5
```
`>>> [act(5) for act in actions]` _# Runs __repr__ not __str__!_
```
[25, 7, 15, −5]
```
`>>> table = {act(5): act for act in actions}` _# 2.6/3.0 dict comprehension_
```
>>> for (key, value) in table.items():
```
`... |
print('{0:2} => {1}'.format(key, value))` _# 2.6/3.0 str.format_
```
...
-5 => <class '__main__.Negate'>
25 => <function square at 0x025D4978>
15 => <bound method Product.method of <__main__.Product object at 0x025D0F90>>
7 => <__main__.Sum object at 0x025D0F70>
```
**|**
-----
As you can see, bound meth... |
For other examples of bound
methods at work, see the upcoming sidebar “Why You Will Care: Bound Methods and
Callbacks” as well as the prior chapter’s discussion of callback handlers in the section
on the method __call__.
###### Why You Will Care: Bound Methods and Callbacks
Because bound methods automatically pair an... |
One of the most common
places you’ll see this idea put to work is in code that registers methods as event callback
handlers in the tkinter GUI interface (named Tkinter in Python 2.6). |
Here’s the simple
case:
```
def handler():
...use globals for state...
...
widget = Button(text='spam', command=handler)
```
To register a handler for button click events, we usually pass a callable object that takes
no arguments to the command keyword argument. |
Function names (and lambdas) work
here, and so do class methods, as long as they are bound methods:
```
class MyWidget:
def handler(self):
...use self.attr for state...
def makewidgets(self):
b = Button(text='spam', command=self.handler)
```
Here, the event handler is self.handler—a bou... |
Because self will refer to the original instance when handler
```
is later invoked on events, the method will have access to instance attributes that can
retain state between events. |
With simple functions, state normally must be retained in
global variables or enclosing function scopes instead. |
See also the discussion of
```
__call__ operator overloading in Chapter 29 for another way to make classes compat
```
ible with function-based APIs.
###### Multiple Inheritance: “Mix-in” Classes
Many class-based designs call for combining disparate sets of methods. |
In a `class`
statement, more than one superclass can be listed in parentheses in the header line.
When you do this, you use something called multiple inheritance—the class and its
instances inherit names from all the listed superclasses.
**|**
-----
When searching for an attribute, Python’s inheritance search trave... |
Technically, because any
of the superclasses may have superclasses of its own, this search can be a bit more
complex for larger class tress:
- In classic classes (the default until Python 3.0), the attribute search proceeds depthfirst all the way to the top of the inheritance tree, and then from left to right.
- In... |
For instance, a person may be an engineer, a writer, a musician, and so on, and
inherit properties from all such sets. |
With multiple inheritance, objects obtain the
union of the behavior in all their superclasses.
Perhaps the most common way multiple inheritance is used is to “mix in” generalpurpose methods from superclasses. |
Such superclasses are usually called _mix-in_
_classes—they provide methods you add to application classes by inheritance. |
In a sense,_
mix-in classes are similar to modules: they provide packages of methods for use in their
client subclasses. |
Unlike simple functions in modules, though, methods in mix-ins also
have access to the self instance, for using state information and other methods. |
The
next section demonstrates one common use case for such tools.
###### Coding Mix-in Display Classes
As we’ve seen, Python’s default way to print a class instance object isn’t incredibly
useful:
```
>>> class Spam:
```
`... |
def __init__(self):` _# No __repr__ or __str___
```
... |
self.data1 = "food"
...
>>> X = Spam()
```
`>>> print(X)` _# Default: class, address_
```
<__main__.Spam object at 0x00864818> # Displays "instance" in Python 2.6
```
As you saw in Chapter 29 when studying operator overloading, you can provide a
```
__str__ or __repr__ method to implement a custom string re... |
Defining a display method in a mix-in superclass once
enables us to reuse it anywhere we want to see a custom display format. |
We’ve already
seen tools that do related work:
**|**
-----
- Chapter 27’s AttrDisplay class formatted instance attributes in a generic __str__
method, but it did not climb class trees and was used in single-inheritance mode
only.
- Chapter 28’s _classtree.py module defined functions for climbing and sketching_
c... |
We’ll also use
our tools in multiple-inheritance mode and deploy coding techniques that make classes
better suited to use as generic tools.
###### Listing instance attributes with __dict__
Let’s get started with the simple case—listing attributes attached to an instance. |
The
following class, coded in the file _lister.py, defines a mix-in called_ `ListInstance that`
overloads the __str__ method for all classes that include it in their header lines. |
Because
this is coded as a class, ListInstance is a generic tool whose formatting logic can be
used for instances of any subclass:
_# File lister.py_
```
class ListInstance:
"""
Mix-in class that provides a formatted print() or str() of
instances via inheritance of __str__, coded here; displays
insta... |
The dictionary’s keys are sorted to
finesse any ordering differences across Python releases.
In these respects, ListInstance is similar to Chapter 27’s attribute display; in fact, it’s
largely just a variation on a theme. |
Our class here uses two additional techniques,
though:
- It displays the instance’s memory address by calling the id built-function, which
returns any object’s address (by definition, a unique object identifier, which will
be useful in later mutations of this code).
- It uses the pseudoprivate naming pattern for it... |
As
we learned earlier in his chapter, Python automatically localizes any such name to
its enclosing class by expanding the attribute name to include the class name (in
this case, it becomes `_ListInstance__attrnames). |
This holds true for both class`
attributes (like methods) and instance attributes attached to self. |
This behavior is
useful in a general tool like this, as it ensures that its names don’t clash with any
names used in its client subclasses.
Because `ListInstance defines a` `__str__ operator overloading method, instances de-`
rived from this class display their attributes automatically when printed, giving a bit
more ... |
Here is the class in action, in single-inheritance
mode (this code works the same in both Python 3.0 and 2.6):
```
>>> from lister import ListInstance
```
`>>> class Spam(ListInstance):` _# Inherit a __str__ method_
```
... |
def __init__(self):
... |
self.data1 = 'food'
...
>>> x = Spam()
```
`>>> print(x)` _# print() and str() run __str___
```
<Instance of Spam, address 40240880:
name data1=food
>
```
You can also fetch the listing output as a string without printing it with str, and interactive echoes still use the default format:
```
>>> str(x)... |
This is where multiple inheritance comes in handy: by
adding ListInstance to the list of superclasses in a class header (i.e., mixing it in), you
get its __str__ “for free” while still inheriting from the existing superclass(es). |
The file
_testmixin.py demonstrates:_
**|**
-----
_# File testmixin.py_
```
from lister import * # Get lister tool classes
class Super:
def __init__(self): # Superclass __init__
self.data1 = 'spam' # Create instance attrs
def ham(self):
pass
class Sub(Super, ListInstanc... |
When you make a Sub instance and print it,
you automatically get the custom representation mixed in from ListInstance (in this
case, this script’s output is the same under both Python 3.0 and 2.6, except for object
addresses):
```
C:\misc> C:\python30\python testmixin.py
<Instance of Sub, address 40962576:
na... |
In a sense, mix-in classes are
the class equivalent of modules—packages of methods useful in a variety of clients. |
For
example, here is Lister working again in single-inheritance mode on a different class’s
instances, with import and attributes set outside the class:
```
>>> import lister
>>> class C(lister.ListInstance): pass
...
>>> x = C()
>>> x.a = 1; x.b = 2; x.c = 3
>>> print(x)
<Instance of C, address 40961776:... |
Since it’s now officially “later,” let’s move on to the next section
to see what such an extension might look like.
###### Listing inherited attributes with dir
As it is, our Lister mix-in displays instance attributes only (i.e., names attached to the
instance object itself). |
It’s trivial to extend the class to display all the attributes accessible from an instance, though—both its own and those it inherits from its classes. |
The
trick is to use the dir built-in function instead of scanning the instance’s __dict__ dictionary; the latter holds instance attributes only, but the former also collects all inherited attributes in Python 2.2 and later.
The following mutation codes this scheme; I’ve renamed it to facilitate simple testing,
but if ... |
This version also must use
the getattr built-in function to fetch attributes by name string instead of using instance
attribute dictionary indexing—getattr employs the inheritance search protocol, and
some of the names we’re listing here are not stored on the instance itself.
**|**
-----
To test the new version, ch... |
In Python 2.6, we get the following; notice the name
mangling at work in the lister’s method name (I shortened its full value display to fit
on this page):
```
C:\misc> c:\python26\python testmixin.py
<Instance of Sub, address 40073136:
name _ListInherited__attrnames=<bound method Sub.__attrnames of <...more.... |
Because
so many names are inherited from the default superclass, I’ve omitted many here; run
this on your own for the full listing:
```
C:\misc> c:\python30\python testmixin.py
<Instance of Sub, address 40831792:
name _ListInherited__attrnames=<bound method Sub.__attrnames of <...more...>>
name __class_... |
With __repr__, this code will loop—
```
displaying the value of a method triggers the __repr__ of the method’s class, in order
to display the class. |
That is, if the lister’s __repr__ tries to display a method, displaying
the method’s class will trigger the lister’s `__repr__ again. Subtle, but true! |
Change`
**|**
-----
```
__str__ to __repr__ here to see this for yourself. |
If you must use __repr__ in such a
```
context, you can avoid the loops by using isinstance to compare the type of attribute
values against types.MethodType in the standard library, to know which items to skip.
###### Listing attributes per object in class trees
Let’s code one last extension. |
As it is, our lister doesn’t tell us which class an inherited
name comes from. |
As we saw in the classtree.py example near the end of Chapter 28,
though, it’s straightforward to climb class inheritance trees in code. |
The following mixin class makes use of this same technique to display attributes grouped by the classes
they live in—it sketches the full class tree, displaying attributes attached to each object
along the way. |
It does so by traversing the inheritance tree from an instance’s
```
__class__ to its class, and then from the class’s __bases__ to all superclasses recursively,
```
scanning object __dicts__s along the way:
_# File lister.py, continued_
```
class ListTree:
"""
Mix-in that returns an __str__ trace of the en... |
Also see how this version uses the Python
3.0 and 2.6 string format method instead of % formatting expressions, to make substitutions clearer; when many substitutions are applied like this, explicit argument numbers may make the code easier to decipher. |
In short, in this version we exchange the
first of the following lines for the second:
```
return '<Instance of %s, address %s:\n%s%s>' % (...) # Expression
return '<Instance of {0}, address {1}:\n{2}{3}>'.format(...) # Method
```
Now, change testmixin.py to inherit from this new class again to test:
`... |
Also observe how the lister’s
```
__visited table has its name mangled in the instance’s attribute dictionary; unless we’re
```
very unlucky, this won’t clash with other data there.
Under Python 3.0, we get extra attributes and superclasses again. |
Notice that unbound
methods are simple functions in 3.0, as described in an earlier note in this chapter (and
that again, I’ve deleted most built-in attributes in object to save space here; run this on
your own for the complete listing):
```
C:\misc> c:\python30\python testmixin.py
<Instance of Sub, address 4063521... |
Like the transitive module reloader of Chapter 24, a dictionary works
to avoid repeats and cycles here because class objects may be dictionary keys; a set
would provide similar functionality.
This version also takes care to avoid large internal objects by skipping __X__ names
again. |
If you comment out the test for these names, their values will display normally.
Here’s an excerpt from the output in 2.6 with this temporary change made (it’s much
larger in its entirety, and it gets even worse in 3.0, which is why these names are probably
better skipped!):
```
C:\misc> c:\python26\python testmixin.... |
In general, you’ll want to name List
```
Tree first (leftmost) in a class header, so its __str__ is picked up; Button has one, too,
```
and the leftmost superclass is searched first in multiple inheritance. |
The output of
the following is fairly massive (18K characters), so run this code on your own to see
the full listing (and if you’re using Python 2.6, recall that you should use Tkinter for
the module name instead of tkinter):
```
>>> from lister import ListTree
```
`>>> from tkinter import Button` _# Both classes ha... |
We’ll also
extend this code in the exercises at the end of this part of the book, to list superclass
names in parentheses at the start of instance and class displays.
The main point here is that OOP is all about code reuse, and mix-in classes are a
powerful example. |
Like almost everything else in programming, multiple inheritance
can be a useful device when applied well. |
In practice, though, it is an advanced feature
and can become complicated if used carelessly or excessively. We’ll revisit this topic as
a gotcha at the end of the next chapter. |
In that chapter, we’ll also meet the new-style
class model, which modifies the search order for one special multiple inheritance case.
_Supporting slots: Because they scan instance dictionaries, the_
```
ListInstance and ListTree classes presented here don’t directly support
```
attributes stored in slots—a ne... |
For example, if in` _textmixin.py we assign_
```
__slots__=['data1'] in Super and __slots__=['data3'] in Sub, only the
data2 attribute is displayed in the instance by these two lister classes;
ListTree also displays data1 and data3, but as attributes of the Super
```
and Sub class objects and with... |
Since instances
inherit only the lowest class’s __slots__, you may also need to come up
with a policy when `__slots__ lists appear in multiple superclasses`
(ListTree already displays them as class attributes). |
`ListInherited is`
immune to all this, because dir results combine both __dict__ names
and all classes’ __slots__ names.
Alternatively, as a policy we could simply let our code handle slot-based
attributes as it currently does, rather than complicating it for a rare,
advanced feature. |
Slots and normal instance attributes are different
kinds of names. |
We’ll investigate slots further in the next chapter; I
omitted addressing them in these examples to avoid a forward
dependency (not counting this note, of course!)—not exactly a valid
design goal, but reasonable for a book.
**|**
-----
###### Classes Are Objects: Generic Object Factories
Sometimes, class-based des... |
The factory design pattern allows
such a deferred approach. |
Due in large part to Python’s flexibility, factories can take
multiple forms, some of which don’t seem special at all.
Because classes are objects, it’s easy to pass them around a program, store them in data
structures, and so on. |
You can also pass classes to functions that generate arbitrary
kinds of objects; such functions are sometimes called factories in OOP design circles.
Factories are a major undertaking in a strongly typed language such as C++ but are
almost trivial to implement in Python. |
The call syntax we met in Chapter 18 can call
any class with any number of constructor arguments in one step to generate any sort
of instance:[‡]
```
def factory(aClass, *args): # Varargs tuple
return aClass(*args) # Call aClass (or apply in 2.6 only)
class Spam:
def doit(self, message):
pr... |
It expects to be
passed a class object (any class will do) along with one or more arguments for the class’s
constructor. |
The function uses special “varargs” call syntax to call the function and
return an instance.
The rest of the example simply defines two classes and generates instances of both by
passing them to the factory function. |
And that’s the only factory function you’ll ever
need to write in Python; it works for any class and any constructor arguments.
One possible improvement worth noting is that to support keyword arguments in constructor calls, the factory can collect them with a **args argument and pass them along
in the class call, too... |
Hence, the
```
factory function here can also run any callable object, not just a class (despite the argument name). |
Also, as
```
we learned in Chapter 18, Python 2.6 has an alternative to aClass(*args): the apply(aClass, args) built-in
call, which has been removed in Python 3.0 because of its redundancy and limitations.
**|**
-----
By now, you should know that everything is an “object” in Python, including things
like classes, ... |
However, as mentioned at the start of this part of the book, only objects derived from classes are OOP
objects in Python.
###### Why Factories?
So what good is the factory function (besides providing an excuse to illustrate class
objects in this book)? |
Unfortunately, it’s difficult to show applications of this design
pattern without listing much more code than we have space for here. |
In general, though,
such a factory might allow code to be insulated from the details of dynamically configured object construction.
For instance, recall the processor example presented in the abstract in Chapter 25, and
then again as a composition example in this chapter. |
It accepts reader and writer objects
for processing arbitrary data streams. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.