Text
stringlengths
1
9.41k
When we add the two instances together, Python runs __add__, which in turn triggers __radd__ by simplifying the left operand. In more realistic classes where the class type may need to be propagated in results, things can become trickier: type testing may be required to tell whether it’s safe to convert and thus avoid...
For instance, without the isinstance test in the following, we could wind up with a Commuter whose val is another Commuter when two instances are added and __add__ triggers __radd__: `>>> class Commuter:` _# Propagate class type in results_ ``` ...
def __init__(self, val): ... self.val = val ... def __add__(self, other): ... if isinstance(other, Commuter): other = other.val ... return Commuter(self.val + other) ...
def __radd__(self, other): ... return Commuter(other + self.val) ... def __str__(self): ...
return '<Commuter: %s>' % self.val ... >>> x = Commuter(88) >>> y = Commuter(99) ``` `>>> print(x + 10)` _# Result is another Commuter instance_ ``` <Commuter: 98> >>> print(10 + y) <Commuter: 109> ``` `>>> z = x + y` _# Not nested: doesn't recur to __radd___ ``` >>> print(z) <Commuter: 187> >>> pri...
The latter is used if the former is absent.
In fact, the prior section’s Commuter ``` class supports += already for this reason, but __iadd__ allows for more efficient in-place changes: ``` >>> class Number: ...
def __init__(self, val): ... self.val = val ``` `... def __iadd__(self, other):` _# __iadd__ explicit: x += y_ `... self.val += other` _# Usually returns self_ ``` ...
return self ... >>> x = Number(5) >>> x += 1 >>> x += 1 >>> x.val 7 >>> class Number: ... def __init__(self, val): ... self.val = val ``` `...
def __add__(self, other):` _# __add__ fallback: x = (x + y)_ `...
return Number(self.val + other)` _# Propagates class type_ ``` ... >>> x = Number(5) >>> x += 1 >>> x += 1 >>> x.val 7 ``` Every binary operator has similar right-side and in-place overloading methods that work the same (e.g., __mul__, __rmul__, and __imul__).
Right-side methods are an advanced topic and tend to be fairly rarely used in practice; you only code them when you need operators to be commutative, and then only if you need to support such operators at all.
For instance, a Vector class may use these tools, but an Employee or ``` Button class probably would not. ###### Call Expressions: __call__ ``` The __call__ method is called when your instance is called.
No, this isn’t a circular definition—if defined, Python runs a __call__ method for function call expressions applied to your instances, passing along whatever positional or keyword arguments were sent: ``` >>> class Callee: ``` `...
def __call__(self, *pargs, **kargs):` _# Intercept instance calls_ `...
print('Called:', pargs, kargs)` _# Accept arbitrary arguments_ ``` ... >>> C = Callee() ``` `>>> C(1, 2, 3)` _# C is a callable object_ **|** ----- ``` Called: (1, 2, 3) {} >>> C(1, 2, 3, x=4, y=5) Called: (1, 2, 3) {'y': 5, 'x': 4} ``` More formally, all the argument-passing modes we explored in Chapte...
For example, the method definitions: ``` class C: def __call__(self, a, b, c=5, d=6): ... # Normals and defaults class C: def __call__(self, *pargs, **kargs): ...
# Collect arbitrary arguments class C: def __call__(self, *pargs, d=6, **kargs): ...
# 3.0 keyword-only argument ``` all match all the following instance calls: ``` X = C() X(1, 2) # Omit defaults X(1, 2, 3, 4) # Positionals X(a=1, b=2, d=4) # Keywords X(*[1, 2], **dict(c=3, d=4)) # Unpack arbitrary arguments X(1, *(2,), c=...
def __init__(self, value):` _# Accept just one argument_ ``` ... self.value = value ... def __call__(self, other): ...
return self.value * other ... ``` `>>> x = Prod(2)` _# "Remembers" 2 in state_ `>>> x(3)` _# 3 (passed) * 2 (state)_ ``` 6 >>> x(4) 8 ``` In this example, the __call__ may seem a bit gratuitous at first glance.
A simple method can provide similar utility: ``` >>> class Prod: ... def __init__(self, value): ... self.value = value ... def comp(self, other): ...
return self.value * other ... ``` **|** ----- ``` >>> x = Prod(3) >>> x.comp(3) 9 >>> x.comp(4) 12 ``` However, __call__ can become more useful when interfacing with APIs that expect functions—it allows us to code objects that conform to an expected function call interface, but also retain state inform...
In fact, it’s probably the third most commonly used operator overloading method, behind the __init__ constructor and the __str__ and __repr__ display-format alternatives. ###### Function Interfaces and Callback-Based Code As an example, the tkinter GUI toolkit (named Tkinter in Python 2.6) allows you to register func...
callbacks); when events occur, tkinter calls the registered objects.
If you want an event handler to retain state between events, you can register either a class’s bound method or an instance that conforms to the expected interface with __call__.
In this section’s code, both x.comp from the second example and x from the first can pass as function-like objects this way. I’ll have more to say about bound methods in the next chapter, but for now, here’s a hypothetical example of __call__ applied to the GUI domain.
The following class defines an object that supports a function-call interface, but also has state information that remembers the color a button should change to when it is later pressed: ``` class Callback: def __init__(self, color): # Function + state information self.color = color def __call__(...
Because it retains state as instance attributes, though, it remembers what to do: ``` cb1() # On events: prints 'blue' cb2() # Prints 'green' ``` In fact, this is probably the best way to retain state information in the Python language—better than the techniques discussed earl...
With OOP, the state remembered is made explicit with attribute assignments. Before we move on, there are two other ways that Python programmers sometimes tie information to a callback function like this.
One option is to use default arguments in ``` lambda functions: cb3 = (lambda color='red': 'turn ' + color) # Or: defaults print(cb3()) ``` The other is to use bound methods of a class.
A bound method object is a kind of object that remembers the self instance and the referenced function.
A bound method may therefore be called as a simple function without an instance later: ``` class Callback: def __init__(self, color): # Class with state information self.color = color def changeColor(self): # A normal named method print('turn', self.color) cb1 = Callback('blue') ...
Because __call__ allows us to attach state information to a callable object, it’s a natural implementation technique for a function that must remember and call another function. ###### Comparisons: __lt__, __gt__, and Others As suggested in Table 29-1, classes can define methods to catch all six comparison operators:...
These methods are generally straightforward to use, but keep the following qualifications in mind: **|** ----- - Unlike the `__add__/__radd__ pairings discussed earlier, there are no right-side` variants of comparison methods.
Instead, reflective methods are used when only one operand supports comparison (e.g., `__lt__ and` `__gt__ are each other’s` reflection). - There are no implicit relationships among the comparison operators.
The truth of ``` == does not imply that != is false, for example, so both __eq__ and __ne__ should ``` be defined to ensure that both operators behave correctly. - In Python 2.6, a __cmp__ method is used by all comparisons if no more specific comparison methods are defined; it returns a number that is less than, e...
This method often uses the `cmp(x, y) built-in to compute its result.
Both the` `__cmp__ method and the` ``` cmp built-in function are removed in Python 3.0: use the more specific methods ``` instead. We don’t have space for an in-depth exploration of comparison methods, but as a quick introduction, consider the following class and test code: ``` class C: data = 'spam' def ...
The following produces the same result under 2.6, for example, but fails in 3.0 because __cmp__ is no longer used: ``` class C: data = 'spam' # 2.6 only def __cmp__(self, other): # __cmp__ not used in 3.0 return cmp(self.data, other) # cmp not defined in 3.0 X = C() print(X > 'h...
If we change the prior class to the following to try to simulate the cmp call, the code still works in 2.6 but fails in 3.0: ``` class C: data = 'spam' def __cmp__(self, other): return (self.data > other) - (self.data < other) ``` So why, you might be asking, did I just show you a comparison method tha...
While it would be easier to erase history entirely, this book is designed to support both 2.6 and 3.0 readers.
Because `__cmp__ may appear in code 2.6 readers must reuse or` maintain, it’s fair game in this book.
Moreover, __cmp__ was removed more abruptly than the __getslice__ method described earlier, and so may endure longer.
If you use 3.0, though, or care about running your code under 3.0 in the future, don’t use __cmp__ anymore: use the more specific comparison methods instead. ###### Boolean Tests: __bool__ and __len__ As mentioned earlier, classes may also define methods that give the Boolean nature of their instances—in Boolean cont...
The first of these generally uses object state or other information to produce a Boolean result: ``` >>> class Truth: ...
def __bool__(self): return True ... >>> X = Truth() >>> if X: print('yes!') ... yes! >>> class Truth: ...
def __bool__(self): return False ... >>> X = Truth() >>> bool(X) False ``` If this method is missing, Python falls back on length because a nonempty object is considered true (i.e., a nonzero length is taken to mean the object is true, and a zero length means it is false): ``` >>> class Truth: ...
def __len__(self): return 0 ... >>> X = Truth() >>> if not X: print('no!') ``` **|** ----- ``` ... no! ``` If both methods are present Python prefers __bool__ over __len__, because it is more specific: ``` >>> class Truth: ``` `...
def __bool__(self): return True` _# 3.0 tries __bool__ first_ `...
def __len__(self): return 0` _# 2.6 tries __len__ first_ ``` ... >>> X = Truth() >>> if X: print('yes!') ... yes! ``` If neither truth method is defined, the object is vacuously considered true (which has potential implications for metaphysically inclined readers!): ``` >>> class Truth: ...
pass ... >>> X = Truth() >>> bool(X) True ``` And now that we’ve managed to cross over into the realm of philosophy, let’s move on to look at one last overloading context: object demise. ###### Booleans in Python 2.6 Python 2.6 users should use __nonzero__ instead of __bool__ in all of the code in the sectio...
Python 3.0 renamed the 2.6 __nonzero__ method to __bool__, but Boolean tests work the same otherwise (both 3.0 and 2.6 use __len__ as a fallback). If you don’t use the 2.6 name, the very first test in this section will work the same for you anyhow, but only because __bool__ is not recognized as a special method name i...
def __bool__(self): ... print('in bool') ...
return False ... >>> X = C() >>> bool(X) in bool False >>> if X: print(99) ... in bool ``` **|** ----- ###### Object Destruction: __del__ We’ve seen how the __init__ constructor is called whenever an instance is generated. Its counterpart, the destructor method __del__, is run autom...
def __init__(self, name='unknown'): ... print('Hello', name) ... self.name = name ... def __del__(self): ...
print('Goodbye', self.name) ... >>> brian = Life('Brian') Hello Brian >>> brian = 'loretta' Goodbye Brian ``` **|** ----- Here, when brian is assigned a string, we lose the last reference to the Life instance and so trigger its destructor method.
This works, and it may be useful for implementing some cleanup activities (such as terminating server connections).
However, destructors are not as commonly used in Python as in some OOP languages, for a number of reasons. For one thing, because Python automatically reclaims all space held by an instance when the instance is reclaimed, destructors are not necessary for space management.[*] For another, because you cannot always eas...
Exceptions raised within it, for example, simply print a warning message to sys.stderr (the standard error stream) rather than triggering an exception event, because of the unpredictable context under which it is run by the garbage collector.
In addition, cyclic (a.k.a.
circular) references among objects may prevent garbage collection from happening when you expect it to; an optional cycle detector, enabled by default, can automatically collect such objects eventually, but only if they do not have __del__ methods.
Since this is relatively obscure, we’ll ignore further details here; see Python’s standard manuals’ coverage of both ``` __del__ and the gc garbage collector module for more information. ###### Chapter Summary ``` That’s as many overloading examples as we have space for here.
Most of the other operator overloading methods work similarly to the ones we’ve explored, and all are just hooks for intercepting built-in type operations; some overloading methods, for example, have unique argument lists or return values.
We’ll see a few others in action later in the book: - Chapter 33 uses the `__enter__ and` `__exit__ with statement context manager` methods. - Chapter 37 uses the __get__ and __set__ class descriptor fetch/set methods. - Chapter 39 uses the __new__ object creation method in the context of metaclasses. - In the c...
However, as mentioned in Chapter 9, it’s better to explicitly call file close methods because auto-close-on-reclaim is a feature of the implementation, not of the language itself (this behavior can vary under Jython, for instance). **|** ----- In addition, some of the methods we’ve studied here, such as __call__ an...
For complete coverage, though, I’ll defer to other documentation sources—see Python’s standard language manual or reference books for details on additional overloading methods. In the next chapter, we leave the realm of class mechanics behind to explore common design patterns—the ways that classes are commonly used an...
Before you read on, though, take a moment to work though the chapter quiz below to review the concepts we’ve covered. ###### Test Your Knowledge: Quiz 1.
What two operator overloading methods can you use to support iteration in your classes? 2. What two operator overloading methods handle printing, and in what contexts? 3.
How can you intercept slice operations in a class? 4. How can you catch in-place addition in a class? 5. When should you provide operator overloading? ###### Test Your Knowledge: Answers 1.
Classes can support iteration by defining (or inheriting) __getitem__ or __iter__. In all iteration contexts, Python tries to use __iter__ (which returns an object that supports the iteration protocol with a `__next__ method) first: if no` `__iter__ is` found by inheritance search, Python falls back on the __getitem__ ...
The __str__ and __repr__ methods implement object print displays.
The former is called by the print and str built-in functions; the latter is called by print and str if there is no __str__, and always by the repr built-in, interactive echoes, and nested appearances.
That is, __repr__ is used everywhere, except by print and str when a `__str__ is defined.
A` `__str__ is usually used for user-friendly displays;` ``` __repr__ gives extra details or the object’s as-code form. ``` 3.
Slicing is caught by the __getitem__ indexing method: it is called with a slice object, instead of a simple index. In Python 2.6, __getslice__ (defunct in 3.0) may be used as well. 4.
In-place addition tries __iadd__ first, and __add__ with an assignment second. The same pattern holds true for all binary operators.
The __radd__ method is also available for right-side addition. **|** ----- 5.
When a class naturally matches, or needs to emulate, a built-in type’s interfaces. For example, collections might imitate sequence or mapping interfaces.
You generally shouldn’t implement expression operators if they don’t naturally map to your objects, though—use normally named methods instead. **|** ----- ----- ###### CHAPTER 30 ### Designing with Classes So far in this part of the book, we’ve concentrated on using Python’s OOP tool, the class.
But OOP is also about design issues—i.e., how to use classes to model useful objects.
This chapter will touch on a few core OOP ideas and present some additional examples that are more realistic than those shown so far. Along the way, we’ll code some common OOP design patterns in Python, such as inheritance, composition, delegation, and factories.
We’ll also investigate some designfocused class concepts, such as pseudoprivate attributes, multiple inheritance, and bound methods.
Many of the design terms mentioned here require more explanation than I can provide in this book; if this material sparks your curiosity, I suggest exploring a text on OOP design or design patterns as a next step. ###### Python and OOP Let’s begin with a review—Python’s implementation of OOP can be summarized by thre...
We’ve also talked about Python’s polymorphism a few times already; it flows from Python’s lack of type declarations.
Because attributes are always resolved at runtime, objects that implement the same interfaces are interchangeable; clients don’t need to know what sorts of objects are implementing the methods they call. ----- Encapsulation means packaging in Python—that is, hiding implementation details behind an object’s interface...
It does not mean enforced privacy, though that can be implemented with code, as we’ll see in Chapter 38.
Encapsulation allows the implementation of an object’s interface to be changed without impacting the users of that object. ###### Overloading by Call Signatures (or Not) Some OOP languages also define polymorphism to mean overloading functions based on the type signatures of their arguments.
But because there are no type declarations in Python, this concept doesn’t really apply; polymorphism in Python is based on object _interfaces, not types._ You can try to overload methods by their argument lists, like this: ``` class C: def meth(self, x): ... def meth(self, x, y, z): ... ``` Thi...
That way, it will be useful for a broader category of types and applications, both now and in the future: ``` class C: def meth(self, x): x.operation() # Assume x does the right thing ``` It’s also generally considered better to use distinct method names for distinct operations, rather than relyin...
The next section begins a tour of some of the ways larger programs use classes to their advantage. **|** ----- ###### OOP and Inheritance: “Is-a” Relationships We’ve explored the mechanics of inheritance in depth already, but I’d like to show you an example of how it can be used to model real-world relationships.
From a programmer’s point of view, inheritance is kicked off by attribute qualifications, which trigger searches for names in instances, their classes, and then any superclasses.
From a designer’s point of view, inheritance is a way to specify set membership: a class defines a set of properties that may be inherited and customized by more specific sets (i.e., subclasses). To illustrate, let’s put that pizza-making robot we talked about at the start of this part of the book to work.
Suppose we’ve decided to explore alternative career paths and open a pizza restaurant. One of the first things we’ll need to do is hire employees to serve customers, prepare the food, and so on.
Being engineers at heart, we’ve decided to build a robot to make the pizzas; but being politically and cybernetically correct, we’ve also decided to make our robot a full-fledged employee with a salary. Our pizza shop team can be defined by the four classes in the example file, _employees.py.
The most general class, Employee, provides common behavior such as_ bumping up salaries (giveRaise) and printing (__repr__).
There are two kinds of employees, and so two subclasses of Employee: Chef and Server. Both override the inherited ``` work method to print more specific messages.
Finally, our pizza robot is modeled by an ``` even more specific class: PizzaRobot is a kind of Chef, which is a kind of Employee.
In OOP terms, we call these relationships “is-a” links: a robot is a chef, which is a(n) employee.
Here’s the employees.py file: ``` class Employee: def __init__(self, name, salary=0): self.name = name self.salary = salary def giveRaise(self, percent): self.salary = self.salary + (self.salary * percent) def work(self): print(self.name, "does stuff") def __repr__(self): ...