Text
stringlengths
1
9.41k
def delegate(self): ... self.action() ... @abstractmethod ... def action(self): ...
pass ... >>> X = Super() TypeError: Can't instantiate abstract class Super with abstract methods action >>> class Sub(Super): pass ... >>> X = Sub() TypeError: Can't instantiate abstract class Sub with abstract methods action >>> class Sub(Super): ...
def action(self): print('spam') ... >>> X = Sub() >>> X.delegate() spam ``` **|** ----- Coded this way, a class with an abstract method cannot be instantiated (that is, we cannot create an instance by calling it) unless all of its abstract methods have been defined in subclasses.
Although this requires more code, the advantage of this approach is that errors for missing methods are issued when we attempt to make an instance of the class, not later when we try to call a missing method.
This feature may also be used to define an expected interface, automatically verified in client classes. Unfortunately, this scheme also relies on two advanced language tools we have not met yet—function decorators, introduced in Chapter 31 and covered in depth in Chapter 38, as well as _metaclass declarations, mentio...
See Python’s standard manuals for more on this, as well as precoded abstract superclasses Python provides. ###### Namespaces: The Whole Story Now that we’ve examined class and instance objects, the Python namespace story is complete.
For reference, I’ll quickly summarize all the rules used to resolve names here. The first things you need to remember are that qualified and unqualified names are treated differently, and that some scopes serve to initialize object namespaces: - Unqualified names (e.g., X) deal with scopes. - Qualified attribute na...
For class and instance objects, the reference rules are augmented to include the inheritance search procedure: **|** ----- _Assignment (object.X =_ `value)` Creates or alters the attribute name X in the namespace of the object being qualified, and none other.
Inheritance-tree climbing happens only on attribute reference, not on attribute assignment. _Reference (object.X)_ For class-based objects, searches for the attribute name `X in` `object, then in all` accessible classes above it, using the inheritance search procedure.
For nonclass objects such as modules, fetches X from object directly. ###### The “Zen” of Python Namespaces: Assignments Classify Names With distinct search procedures for qualified and unqualified names, and multiple lookup layers for both, it can sometimes be difficult to tell where a name will wind up going.
In Python, the place where you assign a name is crucial—it fully determines the scope or object in which a name will reside.
The file manynames.py illustrates how this principle translates to code and summarizes the namespace ideas we have seen throughout this book: _# manynames.py_ ``` X = 11 # Global (module) name/attribute (X, or manynames.X) def f(): print(X) # Access global X (11) def g(): X = 22 ...
Because this name is assigned in five` different locations, though, all five Xs in this program are completely different variables. From top to bottom, the assignments to X here generate: a module attribute (11), a local variable in a function (22), a class attribute (33), a local variable in a method (44), and an inst...
Although all five are named X, the fact that they are all assigned at different places in the source code or to different objects makes all of these unique variables. You should take the time to study this example carefully because it collects ideas we’ve been exploring throughout the last few parts of this book.
When it makes sense to you, you will have achieved a sort of Python namespace nirvana. Of course, an alternative route to nirvana is to simply run the program and see what happens.
Here’s the remainder of this source file, which makes an instance and prints all the Xs that it can fetch: **|** ----- _# manynames.py, continued_ ``` if __name__ == '__main__': print(X) # 11: module (a.k.a.
manynames.X outside file) f() # 11: global g() # 22: local print(X) # 11: module name unchanged obj = C() # Make instance print(obj.X) # 33: class name inherited by instance obj.m() # Attach attribute name X to instance now print(obj.X) ...
obj.X if no X in instance) #print(C.m.X) # FAILS: only visible in method #print(g.X) # FAILS: only visible in function ``` The outputs that are printed when the file is run are noted in the comments in the code; trace through them to see which variable named X is being accessed each time.
Notice in particular that we can go through the class to fetch its attribute (C.X), but we can never fetch local variables in functions or methods from outside their def statements. Locals are visible only to other code within the def, and in fact only live in memory while a call to the function or method is executing....
Also, notice that the instance’s own X is not created until we call I.m()—attributes, like all variables, spring into existence when assigned, and not before.
Normally we create instance attributes by assigning them in class __init__ constructor methods, but this isn’t the only option. **|** ----- Finally, as we learned in Chapter 17, it’s also possible for a function to change names outside itself, with global and (in Python 3.0) nonlocal statements—these statements pro...
The same holds for class and instance objects: attribute qualification is really a dictionary indexing operation internally, and attribute inheritance is just a matter of searching linked dictionaries.
In fact, instance and class objects are mostly just dictionaries with links inside Python.
Python exposes these dictionaries, as well as the links between them, for use in advanced roles (e.g., for coding tools). To help you understand how attributes work internally, let’s work through an interactive session that traces the way namespace dictionaries grow when classes are involved.
We saw a simpler version of this type of code in Chapter 26, but now that we know more about methods and superclasses, let’s embellish it here.
First, let’s define a superclass and a subclass with methods that will store data in their instances: ``` >>> class super: ... def hello(self): ...
self.data1 = 'spam' ... >>> class sub(super): ... def hola(self): ``` **|** ----- ``` ...
self.data2 = 'eggs' ... ``` When we make an instance of the subclass, the instance starts out with an empty namespace dictionary, but it has links back to the class for the inheritance search to follow.
In fact, the inheritance tree is explicitly available in special attributes, which you can inspect.
Instances have a __class__ attribute that links to their class, and classes have a __bases__ attribute that is a tuple containing links to higher superclasses (I’m running this on Python 3.0; name formats and some internal attributes vary slightly in 2.6): ``` >>> X = sub() ``` `>>> X.__dict__` _# Instance namespace...
Most are not used in typical programs, but there are tools that use some of them (e.g., __doc__ holds the docstrings discussed in Chapter 15). **|** ----- Also, observe that Y, a second instance made at the start of this series, still has an empty namespace dictionary at the end, even though X’s dictionary has been...
Again, each instance has an independent namespace dictionary, which starts out empty and can record completely different attributes than those recorded by the namespace dictionaries of other instances of the same class. Because attributes are actually dictionary keys inside Python, there are really two ways to fetch a...
The inherited attribute ``` X.hello, for instance, cannot be accessed by X.__dict__['hello']. ``` Finally, here is the built-in dir function we met in Chapters 4 and 15 at work on class and instance objects.
This function works on anything with attributes: dir(object) is similar to an object.__dict__.keys() call. Notice, though, that dir sorts its list and includes some system attributes.
As of Python 2.2, dir also collects inherited attributes automatically, and in 3.0 it includes names inherited from the object class that is an implied superclass of all classes:[‖] ``` >>> X.__dict__, Y.__dict__ ({'data1': 'spam', 'data3': 'ham', 'data2': 'eggs'}, {}) ``` `>>> list(X.__dict__.keys())` _# Need lis...
For example, because Python now allows built-in types to be subclassed like classes, the contents of dir results for builtin types have expanded to include operator overloading methods, just like our dir results here for user-defined classes under Python 3.0.
In general, attribute names with leading and trailing double underscores are interpreter-specific.
Type subclasses will be discussed further in Chapter 31. **|** ----- _# In Python 3.0:_ ``` >>> dir(X) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', ...more omitted... 'data1', 'data2', 'data3', 'hello', 'hola'] >>> dir(sub) ['__class__', '__delattr__', '__dict__', '__doc__...
Even if you will never use these in the kinds of programs you write, seeing that they are just normal dictionaries will help demystify the notion of namespaces in general. ###### Namespace Links The prior section introduced the special __class__ and __bases__ instance and class attributes, without really explaining w...
In short, these attributes allow you to inspect inheritance hierarchies within your own code.
For example, they can be used to display a class tree, as in the following example: _# classtree.py_ ``` """ Climb inheritance trees using namespace links, displaying higher superclasses with indentation """ def classtree(cls, indent): print('.' * indent + cls.__name__) # Print class name here for s...
This allows the function ``` to traverse arbitrarily shaped class trees; the recursion climbs to the top, and stops at root superclasses that have empty __bases__ attributes.
When using recursion, each active level of a function gets its own copy of the local scope; here, this means that ``` cls and indent are different at each classtree level. ``` Most of this file is self-test code.
When run standalone in Python 3.0, it builds an empty class tree, makes two instances from it, and prints their class tree structures: ``` C:\misc> c:\python26\python classtree.py Tree of <__main__.B instance at 0x02557328> ...B ......A Tree of <__main__.F instance at 0x02557328> ...F ......D .........B...
Of course, we could improve on this output format, and perhaps even sketch it in a GUI display.
Even as is, though, we can import these functions anywhere we want a quick class tree display: **|** ----- ``` C:\misc> c:\python30\python >>> class Emp: pass ... >>> class Person(Emp): pass >>> bob = Person() >>> import classtree >>> classtree.instancetree(bob) Tree of <__main__.Person object at 0x...
You’ll see another when we code the lister.py general-purpose class display tools in the section “Multiple Inheritance: “Mix-in” Classes” on page 756—there, we will extend this technique to also display attributes in each object in a class tree.
And in the last part of this book, we’ll revisit such tools in the context of Python tool building at large, to code tools that implement attribute privacy, argument validation, and more. While not for every Python programmer, access to internals enables powerful development tools. ###### Documentation Strings Revisit...
Docstrings, which we covered in detail in Chapter 15, are string literals that show up at the top of various structures and are automatically saved by Python in the corresponding objects’ __doc__ attributes.
This works for module files, function defs, and classes and methods. Now that we know more about classes and methods, the following file, docstr.py, provides a quick but comprehensive example that summarizes the places where docstrings can show up in your code.
All of these can be triple-quoted blocks: ``` "I am: docstr.__doc__" def func(args): "I am: docstr.func.__doc__" pass class spam: "I am: spam.__doc__ or docstr.spam.__doc__" def method(self, arg): "I am: spam.method.__doc__ or self.method.__doc__" pass ``` **|** ----- The main adva...
Here it is running on our code under Python 2.6 (Python 3.0 shows additional attributes inherited from the implied object superclass in the newstyle class model—run this on your own to see the 3.0 extras, and watch for more about this difference in Chapter 31): ``` >>> help(docstr) Help on module docstr: NAME ...
Both forms are useful tools, and any program documentation is good (as long as it’s accurate, of course!).
As a best-practice rule of thumb, use docstrings for functional documentation (what your objects do) and hash-mark comments for more micro-level documentation (how arcane expressions work). **|** ----- ###### Classes Versus Modules Let’s wrap up this chapter by briefly comparing the topics of this book’s last two ...
Because they’re both about namespaces, the distinction can be confusing.
In short: - Modules —Are data/logic packages —Are created by writing Python files or C extensions —Are used by being imported - Classes —Implement new objects —Are created by class statements —Are used by being called —Always live within a module Classes also support extra features that modules don’t, such as oper...
Although both classes and modules are namespaces, you should be able to tell by now that they are very different things. ###### Chapter Summary This chapter took us on a second, more in-depth tour of the OOP mechanisms of the Python language.
We learned more about classes, methods, and inheritance, and we wrapped up the namespace story in Python by extending it to cover its application to classes.
Along the way, we looked at some more advanced concepts, such as abstract superclasses, class data attributes, namespace dictionaries and links, and manual calls to superclass methods and constructors. Now that we’ve learned all about the mechanics of coding classes in Python, Chapter 29 turns to a specific facet of t...
After that we’ll explore common design patterns, looking at some of the ways that classes are commonly used and combined to optimize code reuse.
Before you read ahead, though, be sure to work though the usual chapter quiz to review what we’ve covered here. ###### Test Your Knowledge: Quiz 1. What is an abstract superclass? 2.
What happens when a simple assignment statement appears at the top level of a ``` class statement? ``` **|** ----- 3.
Why might a class need to manually call the __init__ method in a superclass? 4. How can you augment, instead of completely replacing, an inherited method? 5.
What...was the capital of Assyria? ###### Test Your Knowledge: Answers 1.
An abstract superclass is a class that calls a method, but does not inherit or define it—it expects the method to be filled in by a subclass.
This is often used as a way to generalize classes when behavior cannot be predicted until a more specific subclass is coded.
OOP frameworks also use this as a way to dispatch to client-defined, customizable operations. 2.
When a simple assignment statement (X = Y) appears at the top level of a class statement, it attaches a data attribute to the class (Class.X).
Like all class attributes, this will be shared by all instances; data attributes are not callable method functions, though. 3.
A class must manually call the `__init__ method in a superclass if it defines an` ``` __init__ constructor of its own, but it also must still kick off the superclass’s con ``` struction code.
Python itself automatically runs just one constructor—the lowest one in the tree.
Superclass constructors are called through the class name, passing in the self instance manually: Superclass.__init__(self, ...). 4.
To augment instead of completely replacing an inherited method, redefine it in a subclass, but call back to the superclass’s version of the method manually from the new version of the method in the subclass.
That is, pass the self instance to the superclass’s version of the method manually: Superclass.method(self, ...). 5.
Ashur (or Qalat Sherqat), Calah (or Nimrud), the short-lived Dur Sharrukin (or Khorsabad), and finally Nineveh. **|** ----- ###### CHAPTER 29 ### Operator Overloading This chapter continues our in-depth survey of class mechanics by focusing on operator overloading.
We looked briefly at operator overloading in prior chapters; here, we’ll fill in more details and look at a handful of commonly used overloading methods. Although we won’t demonstrate each of the many operator overloading methods available, those we will code here are a representative sample large enough to uncover the...
Here’s a review of the key ideas behind overloading: - Operator overloading lets classes intercept normal Python operations. - Classes can overload all Python expression operators. - Classes can also overload built-in operations such as printing, function calls, attribute access, etc. - Overloading makes class ...
As we’ve learned, operator overloading methods are never required and generally don’t have defaults; if you don’t code or inherit one, it just means that your class does not support the corresponding operation.
When used, though, these methods allow classes to emulate the interfaces of built-in objects, and so appear more consistent. ----- ###### Constructors and Expressions: __init__ and __sub__ Consider the following simple example: its Number class, coded in the file number.py, provides a method to intercept instance c...
Special methods such as these are the hooks that let you tie into built-in operations: ``` class Number: def __init__(self, start): # On Number(start) self.data = start def __sub__(self, other): # On instance - other return Number(self.data - other) # Result is a new instance ...
Table 29-1 lists a few of the most common; there are many more.
In fact, many overloading methods come in multiple versions (e.g., __add__, __radd__, and __iadd__ for addition), which is one reason there are so many.
See other Python books, or the Python language reference manual, for an exhaustive list of the special method names available. _Table 29-1.
Common operator overloading methods_ **Method** **Implements** **Called for** `__init__` Constructor Object creation: X = Class(args) `__del__` Destructor Object reclamation of X `__add__` Operator + `X + Y, X += Y if no __iadd__` `__or__` Operator | (bitwise OR) `X | Y, X |= Y if no __ior__` `__repr__, __str__...
The mappings from special method names to expressions or operations are predefined by the Python language (and documented in the standard language manual).
For example, the name __add__ always maps to + expressions by Python language definition, regardless of what an __add__ method’s code actually does. Operator overloading methods may be inherited from superclasses if not defined, just like any other methods.
Operator overloading methods are also all optional—if you don’t code or inherit one, that operation is simply unsupported by your class, and attempting it will raise an exception.
Some built-in operations, like printing, have defaults (inherited for the implied object class in Python 3.0), but most built-ins fail for class instances if no corresponding operator overloading method is present. Most overloading methods are used only in advanced programs that require objects to behave like built-in...
We’ve already met the __init__ initialization-time constructor method, and a few of the others in Table 29-1.
Let’s explore some of the additional methods in the table by example. **|** ----- ###### Indexing and Slicing: __getitem__ and __setitem__ If defined in a class (or inherited by it), the __getitem__ method is called automatically for instance-indexing operations.
When an instance X appears in an indexing expression like X[i], Python calls the __getitem__ method inherited by the instance, passing X to the first argument and the index in brackets to the second argument.
For example, the following class returns the square of an index value: ``` >>> class Indexer: ... def __getitem__(self, index): ...
return index ** 2 ... >>> X = Indexer() ``` `>>> X[2]` _# X[i] calls X.__getitem__(i)_ ``` 4 >>> for i in range(5): ``` `...
print(X[i], end=' ')` _# Runs __getitem__(X, i) each time_ ``` ... 0 1 4 9 16 ###### Intercepting Slices ``` Interestingly, in addition to indexing, __getitem__ is also called for slice expressions. Formally speaking, built-in types handle slicing the same way.
Here, for example, is slicing at work on a built-in list, using upper and lower bounds and a stride (see Chapter 7 if you need a refresher on slicing): ``` >>> L = [5, 6, 7, 8, 9] ``` `>>> L[2:4]` _# Slice with slice syntax_ ``` [7, 8] >>> L[1:] [6, 7, 8, 9] >>> L[:-1] [5, 6, 7, 8] >>> L[::2] [5, 7, 9]...
In fact, you can always pass a slice object manually—slice syntax is mostly syntactic sugar for indexing with a slice object: `>>> L[slice(2, 4)]` _# Slice with slice objects_ ``` [7, 8] >>> L[slice(1, None)] [6, 7, 8, 9] >>> L[slice(None, −1)] [5, 6, 7, 8] >>> L[slice(None, None, 2)] [5, 7, 9] ``` **|*...
Our previous class won’t handle slicing because its math assumes integer indexes are passed, but the following class will.
When called for indexing, the argument is an integer as before: ``` >>> class Indexer: ... data = [5, 6, 7, 8, 9] ``` `... def __getitem__(self, index):` _# Called for index or slice_ ``` ...
print('getitem:', index) ``` `...
return self.data[index]` _# Perform index or slice_ ``` ... >>> X = Indexer() ``` `>>> X[0]` _# Indexing sends __getitem__ an integer_ ``` getitem: 0 5 >>> X[1] getitem: 1 6 >>> X[-1] getitem: −1 9 ``` When called for slicing, though, the method receives a slice object, which is simply passed alon...