Text
stringlengths
1
9.41k
The original version of this example manually passed in instances of specialized classes like FileWriter and SocketReader to customize the data streams being processed; later, we passed in hardcoded file, stream, and formatter objects.
In a more dynamic scenario, external devices such as configuration files or GUIs might be used to configure the streams. In such a dynamic world, we might not be able to hardcode the creation of stream interface objects in our scripts, but might instead create them at runtime according to the contents of a configurati...
Factory-style functions or code might come in handy here because they would allow us to fetch and pass in classes that are not hardcoded in our program ahead of time.
Indeed, those classes might not even have existed at all when we wrote our code: ``` classname = ...parse from config file... classarg = ...parse from config file... import streamtypes # Customizable code aclass = getattr(streamtypes, classname) # Fetch from module reader = factory(aclass, clas...
Because this code snippet assumes a` single constructor argument, it doesn’t strictly need factory or apply—we could make an instance with just aclass(classarg).
They may prove more useful in the presence of unknown argument lists, however, and the general factory coding pattern can improve the code’s flexibility. **|** ----- ###### Other Design-Related Topics In this chapter, we’ve seen inheritance, composition, delegation, multiple inheritance, bound methods, and factori...
We’ve really only scratched the surface here in the design patterns domain, though.
Elsewhere in this book you’ll find coverage of other design-related topics, such as: - Abstract superclasses (Chapter 28) - Decorators (Chapters 31 and 38) - Type subclasses (Chapter 31) - Static and class methods (Chapter 31) - Managed attributes (Chapter 37) - Metaclasses (Chapters 31 and 39) For more de...
Although patterns are important in OOP work, and are often more natural in Python than other languages, they are not specific to Python itself. ###### Chapter Summary In this chapter, we sampled common ways to use and combine classes to optimize their reusability and factoring benefits—what are usually considered des...
We studied delegation (wrapping objects in proxy classes), _composition (controlling embedded objects), and inheritance (acquiring behavior from_ other classes), as well as some more esoteric concepts such as pseudoprivate attributes, multiple inheritance, bound methods, and factories. The next chapter ends our look a...
First, though, another quick chapter quiz. ###### Test Your Knowledge: Quiz 1. What is multiple inheritance? 2. What is delegation? 3. What is composition? **|** ----- 4.
What are bound methods? 5. What are pseudoprivate attributes used for? ###### Test Your Knowledge: Answers 1.
Multiple inheritance occurs when a class inherits from more than one superclass; it’s useful for mixing together multiple packages of class-based code.
The left-toright order in class statement headers determines the order of attribute searches. 2.
Delegation involves wrapping an object in a proxy class, which adds extra behavior and passes other operations to the wrapped object. The proxy retains the interface of the wrapped object. 3.
Composition is a technique whereby a controller class embeds and directs a number of objects, and provides an interface all its own; it’s a way to build up larger structures with classes. 4.
Bound methods combine an instance and a method function; you can call them without passing in an instance object explicitly because the original instance is still available. 5.
Pseudoprivate attributes (whose names begin with two leading underscores: __X) are used to localize names to the enclosing class.
This includes both class attributes like methods defined inside the class, and self instance attributes assigned inside the class.
Such names are expanded to include the class name, which makes them unique. **|** ----- ----- ###### CHAPTER 31 ### Advanced Class Topics This chapter concludes our look at OOP in Python by presenting a few more advanced class-related topics: we will survey subclassing built-in types, “new-style” class changes an...
In the interest of completeness, though, we’ll round out our discussion of classes with a brief look at these advanced tools for OOP work. As usual, because this is the last chapter in this part of the book, it ends with a section on class-related “gotchas,” and the set of lab exercises for this part.
I encourage you to work through the exercises to help cement the ideas we’ve studied here. I also suggest working on or studying larger OOP Python projects as a supplement to this book.
As with much in computing, the benefits of OOP tend to become more apparent with practice. _Content note: This chapter collects advanced class topics, but some are_ even too advanced for this chapter to cover well.
Topics such as properties, descriptors, decorators, and metaclasses are only briefly mentioned here, and are covered more fully in the final part of this book.
Be sure to look ahead for more complete examples and extended coverage of some of the subjects that fall into this chapter’s category. ###### Extending Built-in Types Besides implementing new kinds of objects, classes are sometimes used to extend the functionality of Python’s built-in types to support more exotic dat...
For instance, to add queue insert and delete methods to lists, you can code classes that wrap (embed) a list object and export insert and delete methods that process the list specially, like the delegation technique we studied in Chapter 30.
As of Python 2.2, you can also ----- use inheritance to specialize built-in types.
The next two sections show both techniques in action. ###### Extending Types by Embedding Remember those set functions we wrote in Chapters 16 and 18?
Here’s what they look like brought back to life as a Python class.
The following example (the file _setwrapper.py) implements a new set object type by moving some of the set functions_ to methods and adding some basic operator overloading.
For the most part, this class just wraps a Python list with extra set operations. But because it’s a class, it also supports multiple instances and customization by inheritance in subclasses.
Unlike our earlier functions, using classes here allows us to make multiple self-contained set objects with preset data and behavior, rather than passing lists into functions manually: ``` class Set: def __init__(self, value = []): # Constructor self.data = [] # Manages a list self.concat(val...
Because you will interact with and extend this class in an exercise at the end of this chapter, I won’t say much more about this code until Appendix B. ###### Extending Types by Subclassing Beginning with Python 2.2, all the built-in types in the language can now be subclassed directly.
Type-conversion functions such as list, str, dict, and tuple have become built-in type names—although transparent to your script, a type-conversion call (e.g., ``` list('spam')) is now really an invocation of a type’s object constructor. ``` This change allows you to customize or extend the behavior of built-in types ...
Instances of your type subclasses can be used anywhere that the original built-in type can appear.
For example, suppose you have trouble getting used to the fact that Python list offsets begin at 0 instead of 1.
Not to worry—you can always code your own subclass that customizes this core behavior of lists.
The file typesubclass.py shows how: _# Subclass built-in list type/class_ ``` # Map 1..N to 0..N-1; call back to built-in version. class MyList(list): def __getitem__(self, offset): print('(indexing %s at %s)' % (self, offset)) return list.__getitem__(self, offset - 1) if __name__ == '__main__': ...
All it really does is decrement the submitted index and call back to the superclass’s version of indexing, but it’s enough to do the trick: ``` % python typesubclass.py ['a', 'b', 'c'] ['a', 'b', 'c'] (indexing ['a', 'b', 'c'] at 1) a (indexing ['a', 'b', 'c'] at 3) c ['a', 'b', 'c', 'spam'] ['spam', ...
Of course, whether changing indexing this way is a good idea in general is another issue—users of your ``` MyList class may very well be confused by such a core departure from Python sequence ``` behavior.
The ability to customize built-in types this way can be a powerful asset, though. For instance, this coding pattern gives rise to an alternative way to code a set—as a subclass of the built-in list type, rather than a standalone class that manages an embedded list object, as shown earlier in this section.
As we learned in Chapter 5, Python today comes with a powerful built-in set object, along with literal and comprehension syntax for making new sets.
Coding one yourself, though, is still a great way to learn about type subclassing in general. The following class, coded in the file setsubclass.py, customizes lists to add just methods and operators related to set processing.
Because all other behavior is inherited from the built-in list superclass, this makes for a shorter and simpler alternative: ``` class Set(list): def __init__(self, value = []): # Constructor list.__init__([]) # Customizes list self.concat(value) # Copies mutable defaults def inter...
.
. for x in value: # Removes duplicates if not x in self: self.append(x) def __and__(self, other): return self.intersect(other) def __or__(self, other): return self.union(other) def __repr__(self): return 'Set:' + list.__repr__(self) if __name__ == '__main__': x = Set...
Because subclassing core types is an advanced feature, I’ll omit further details here, but I invite you to trace through these results in the code to study its behavior: ``` % python setsubclass.py Set:[1, 3, 5, 7] Set:[2, 1, 4, 5, 6] 4 Set:[1, 5] Set:[2, 1, 4, 5, 6, 3, 7] Set:[1, 5] Set:[1, 3, 5, 7, 2, 4, 6] ...
(For more details, see Programming _Python.) If you’re interested in sets, also take another look at the set object type we_ explored in Chapter 5; this type provides extensive set operations as built-in tools.
Set implementations are fun to experiment with, but they are no longer strictly required in Python today. For another type subclassing example, see the implementation of the bool type in Python 2.3 and later.
As mentioned earlier in the book, bool is a subclass of int with two instances (True and False) that behave like the integers 1 and 0 but inherit custom stringrepresentation methods that display their names. ###### The “New-Style” Class Model In Release 2.2, Python introduced a new flavor of classes, known as “new-st...
In 3.0 the class story has merged, but it remains split for Python 2.X users: - As of Python 3.0, all classes are automatically what we used to call “new-style,” whether they explicitly inherit from object or not.
All classes inherit from object, whether implicitly or explicitly, and all objects are instances of object. - In Python 2.6 and earlier, classes must inherit from object (or another built-in type) to be considered “new-style” and obtain all new-style features. Because all classes are automatically new-style in 3.0, ...
I’ve opted to keep their descriptions in this section separate, however, in deference to users of Python 2.X code—classes in such code acquire new-style features only when they are derived from object. In other words, when Python 3.0 users see descriptions of “new-style” features in this section, they should take them...
The built-in name object is provided to serve as a superclass for new-style classes if no other built-in type is appropriate to use: ``` class newstyle(object): ...normal code... ``` Any class derived from object, or any other built-in type, is automatically treated as a new-style class.
As long as a built-in type is somewhere in the superclass tree, the new class is treated as a new-style class.
Classes not derived from built-ins such as object are considered classic. New-style classes are only slightly different from classic classes, and the ways in which they differ are irrelevant to the vast majority of Python users.
Moreover, the classic class model still available in 2.6 works exactly as it has for almost two decades. In fact, new-style classes are almost completely backward compatible with classic classes in syntax and behavior; they mostly just add a few advanced new features. However, because they modify a handful of class be...
For example, some subtle differences, such as diamond pattern inheritance search and the behavior of built-in operations with managed attribute methods such as __getattr__, can cause some legacy code to fail if left unchanged. The next two sections provide overviews of the ways the new-style classes differ and the new...
Again, because all classes are new-style today, these topics represent changes to Python 2.X readers but simply additional advanced class topics to Python 3.0 readers. ###### New-Style Class Changes New-style classes differ from classic classes in a number of ways, some of which are subtle but can impact existing 2.X...
Here are some of the most prominent ways they differ: _Classes and types merged_ Classes are now types, and types are now classes. In fact, the two are essentially synonyms.
The type(I) built-in returns the class an instance is made from, instead of a generic instance type, and is normally the same as `I.__class__.
Moreover,` classes are instances of the type class, type may be subclassed to customize class creation, and all classes (and hence types) inherit from object. _Inheritance search order_ Diamond patterns of multiple inheritance have a slightly different search order— roughly, they are searched across before up, and more...
This means that they are not called for ``` __X__ operator overloading method names—the search for such names begins at ``` classes, not instances. _New advanced tools_ New-style classes have a set of new class tools, including slots, properties, descriptors, and the `__getattribute__ method.
Most of these have very specific tool-` building purposes. We discussed the third of these changes briefly in a sidebar in Chapter 27, and we’ll revisit it in depth in the contexts of attribute management in Chapter 37 and privacy decorators in Chapter 38.
Because the first and second of the changes just listed can break existing 2.X code, though, let’s explore these in more detail before moving on to new-style additions. ###### Type Model Changes In new-style classes, the distinction between type and class has vanished entirely. Classes themselves are types: the `type...
If fact, there is no real difference between builtin types like lists and strings and user-defined types coded as classes.
This is why we can subclass built-in types, as shown earlier in this chapter—because subclassing a built-in type such as list qualifies a class as new-style, it becomes a user-defined type. Besides allowing us to subclass built-in types, one of the contexts where this becomes most obvious is when we do explicit type t...
With Python 2.6’s classic classes, the type of a class instance is a generic “instance,” but the types of built-in objects are more specific: ``` C:\misc> c:\python26\python ``` `>>> class C: pass` _# Classic classes in 2.6_ ``` ... >>> I = C() ``` `>>> type(I)` _# Instances are made from classes_ ``` <type '...
In fact, the distinction between builtin types and user-defined class types melts away altogether in 3.0: ``` C:\misc> c:\python30\python ``` `>>> class C: pass` _# All classes are new-style in 3.0_ ``` ... >>> I = C() ``` `>>> type(I)` _# Type of instance is class it's made from_ ``` <class '__main__.C'> >...
Technically, each class is generated by a metaclass—a class that is normally either type itself, or a subclass of it customized to augment or manage generated classes.
Besides impacting code that does type testing, this turns out to be an important hook for tool developers.
We’ll talk more about metaclasses later in this chapter, and again in more detail in Chapter 39. ###### Implications for type testing Besides providing for built-in type customization and metaclass hooks, the merging of classes and types in the new-style class model can impact code that does type testing. In Python 3...
This follows from the fact that classes are now types, and an instance’s type is the instance’s class: ``` C:\misc> c:\python30\python >>> class C: pass ... >>> class D: pass ... >>> c = C() >>> d = D() ``` `>>> type(c) == type(d)` _# 3.0: compares the instances' classes_ ``` False >>> type(c), type(...
To truly compare types, the instance `__class__ attributes must be compared (if you care about portability, this` works in 3.0, too, but it’s not required there): ``` C:\misc> c:\python26\python >>> class C: pass ... >>> class D: pass ... >>> c = C() >>> d = D() ``` `>>> type(c) == type(d)` _# 2.6: all i...
However, knowledge of Python’s type model can help demystify the class model in general. ###### All objects derive from “object” One other ramification of the type change in the new-style class model is that because all classes derive (inherit) from the class object either implicitly or explicitly, and because all ty...
Consider the following interaction in Python 3.0 (code an explicit object superclass in 2.6 to make this work equivalently): ``` >>> class C: pass ... >>> X = C() ``` `>>> type(X)` _# Type is now class instance was created from_ ``` <class '__main__.C'> >>> type(C) <class 'type'> ``` As before, the type o...
It is also true, though, that the instance and class are both derived from the built-in object class, since this is an implicit or explicit superclass of every class: **|** ----- ``` >>> isinstance(X, object) True ``` `>>> isinstance(C, object)` _# Classes always inherit from object_ ``` True ``` The same h...
We’ll see examples of the latter later in the book; for now, let’s move ``` on to explore other new-style changes. ###### Diamond Inheritance Change One of the most visible changes in new-style classes is their slightly different inheritance search procedures for the so-called diamond pattern of multiple inheritance...
The diamond pattern is an advanced design concept, is coded only rarely in Python practice, and has not been discussed in this book, so we won’t dwell on this topic in depth. In short, though, with classic classes, the inheritance search procedure is strictly depth first, and then left to right—Python climbs all the w...
In new-style classes, the search is more breadth-first in such cases—Python first looks in any superclasses **|** ----- to the right of the first one searched before ascending all the way to the common superclass at the top.
In other words, the search proceeds across by levels before moving up.
The search algorithm is a bit more complex than this, but this is as much as most programmers need to know. Because of this change, lower superclasses can overload attributes of higher superclasses, regardless of the sort of multiple inheritance trees they are mixed into.
Moreover, the new-style search rule avoids visiting the same superclass more than once when it is accessible from multiple subclasses. ###### Diamond inheritance example To illustrate, consider this simplistic incarnation of the diamond multiple inheritance pattern for classic classes.
Here, D’s superclasses B and C both lead to the same common ancestor, A: ``` >>> class A: ``` `attr = 1` _# Classic (Python 2.6)_ `>>> class B(A):` _# B and C both lead to A_ ``` pass >>> class C(A): attr = 2 >>> class D(B, C): ``` `pass` _# Tries A before C_ ``` >>> x = D() ``` `>>> x.attr` _# ...
That is, it searches D, B, C, and then A, and in this case, stops in C: >>> class A(object): ``` `attr = 1` _# New-style ("object" not required in 3.0)_ ``` >>> class B(A): pass >>> class C(A): attr = 2 >>> class D(B, C): ``` `pass` _# Tries C before A_ ``` >>> x = D() ``` **|** ----- `>>> x...
It also assumes that C is always intended to override A’s attributes in all contexts, which is probably true when it’s used standalone but may not be when it’s mixed into a diamond with classic classes—you might not even know that C may be mixed in like this when you code it. Since it is most likely that the programme...
Otherwise, C could be essentially pointless in a diamond context: it could not customize A and would be used only for names unique to C. ###### Explicit conflict resolution Of course, the problem with assumptions is that they assume things.
If this search order deviation seems too subtle to remember, or if you want more control over the search process, you can always force the selection of an attribute from anywhere in the tree by assigning or otherwise naming the one you want at the place where the classes are mixed together: ``` >>> class A: ``` `att...
New-style classes can similarly emulate classic classes by choosing the attribute above at the place where the classes are mixed together: ``` >>> class A(object): ``` `attr = 1` _# New-style_ ``` >>> class B(A): pass >>> class C(A): ``` **|** ----- ``` attr = 2 >>> class D(B, C): ``` `attr = ...
We might also simply call the desired class explicitly; in practice, this pattern might be more common, especially for things like constructors: ``` class D(B, C): def meth(self): # Redefine lower ... C.meth(self) # Pick C's method by calling ``` Such selections by assignment or call at...
Explicitly resolving the conflicts this way ensures that your code won’t vary per Python version in the future (apart from perhaps needing to derive classes from object or a built-in type for the new-style tools in 2.6). **|** ----- Even without the classic/new-style class divergence, the explicit method resolution...
For instance, if you want part of a superclass on the left and part of a superclass on the right, you might need to tell Python which same-named attributes to choose by using explicit assignments in subclasses.
We’ll revisit this notion in a “gotcha” at the end of this chapter. Also note that diamond inheritance patterns might be more problematic in some cases than I’ve implied here (e.g., what if B and C both have required constructors that call to the constructor in A?).
Since such contexts are rare in real-world Python, we’ll leave this topic outside this book’s scope (but see the `super built-in function for hints—besides` providing generic access to superclasses in single inheritance trees, ``` super supports a cooperative mode for resolving some conflicts in mul ``` tiple in...
Keep in mind, though, that this change primarily affects diamond pattern cases of multiple inheritance; new-style class inheritance works unchanged for most other inheritance tree structures.
Further, it’s not impossible that this entire issue may be of more theoretical than practical importance—because the new-style search wasn’t significant enough to address until Python 2.2 and didn’t become standard until 3.0, it seems unlikely to impact much Python code. Having said that, I should also note that even ...
Hence the new-style search rule not only modifies logical semantics, but also optimizes performance by avoiding visiting the same class more than once. Just as important, the implied object superclass in the new-style model provides default methods for a variety of built-in operations, including the __str__ and __repr...
Run a dir(object) to see which methods are provided.
Without the new-style search order, in multiple inheritance cases the defaults in object would always override redefinitions in user-coded classes, unless they were always made in the leftmost superclass.
In other words, the new-style class model itself makes using the new-style search order more critical! For a more visual example of the implied object superclass in 3.0, and other examples of diamond patterns created by it, see the ListTree class’s output in the lister.py example in the preceding chapter, as well as t...