Text
stringlengths
1
9.41k
For instance, the for loop in this module’s self-test code creates instances of all four classes; each responds differently when asked to work because the work method is different in each.
Really, these classes just simulate real-world objects; work prints a message for the time being, but it could be expanded to do real work later. ###### OOP and Composition: “Has-a” Relationships The notion of composition was introduced in Chapter 25.
From a programmer’s point of view, composition involves embedding other objects in a container object, and activating them to implement container methods.
To a designer, composition is another way to represent relationships in a problem domain.
But, rather than set membership, composition has to do with components—parts of a whole. Composition also reflects the relationships between parts, called a “has-a” relationships.
Some OOP design texts refer to composition as aggregation (or distinguish between the two terms by using aggregation to describe a weaker dependency between **|** ----- container and contained); in this text, a “composition” simply refers to a collection of embedded objects.
The composite class generally provides an interface all its own and implements it by directing the embedded objects. Now that we’ve implemented our employees, let’s put them in the pizza shop and let them get busy.
Our pizza shop is a composite object: it has an oven, and it has employees like servers and chefs.
When a customer enters and places an order, the components of the shop spring into action—the server takes the order, the chef makes the pizza, and so on.
The following example (the file pizzashop.py) simulates all the objects and relationships in this scenario: ``` from employees import PizzaRobot, Server class Customer: def __init__(self, name): self.name = name def order(self, server): print(self.name, "orders from", server) def pay(self, s...
When this module’s self-test code calls the PizzaShop order method, the embedded objects are asked to carry out their actions in turn.
Notice that we make a new Customer object for each order, and we pass on the embedded Server object to ``` Customer methods; customers come and go, but the server is part of the pizza shop ``` composite.
Also notice that employees are still involved in an inheritance relationship; composition and inheritance are complementary tools. **|** ----- When we run this module, our pizza shop handles two orders—one from Homer, and then one from Shaggy: ``` C:\python\examples> python pizzashop.py Homer orders from <Emplo...
As a rule of thumb, classes can represent just about any objects and relationships you can express in a sentence; just replace nouns with classes, and verbs with methods, and you’ll have a first cut at a design. ###### Stream Processors Revisited For a more realistic composition example, recall the generic data strea...
The following file, streams.py, demonstrates one way to code the class: ``` class Processor: def __init__(self, reader, writer): self.reader = reader self.writer = writer def process(self): while 1: data = self.reader.readline() if not data: break data = self.converte...
Coded this way, reader and writer objects are embedded within the class instance (composition), and we supply the conversion logic in a subclass rather than passing in a converter function (inheritance).
The file converters.py shows how: **|** ----- ``` from streams import Processor class Uppercase(Processor): def converter(self, data): return data.upper() if __name__ == '__main__': import sys obj = Uppercase(open('spam.txt'), sys.stdout) obj.process() ``` Here, the Uppercase class inhe...
It needs to define only what is unique about it— the data conversion logic.
When this file is run, it makes and runs an instance that reads from the file spam.txt and writes the uppercase equivalent of that file to the `stdout` stream: ``` C:\lp4e> type spam.txt spam Spam SPAM! C:\lp4e> python converters.py SPAM SPAM SPAM! ``` To process different sorts of streams, pass in dif...
Here, we use an output file instead of a stream: ``` C:\lp4e> python >>> import converters >>> prog = converters.Uppercase(open('spam.txt'), open('spamup.txt', 'w')) >>> prog.process() C:\lp4e> type spamup.txt SPAM SPAM SPAM! ``` But, as suggested earlier, we could also pass in arbitrary objects wrappe...
Here’s a simple example that passes in a writer class that wraps up the text inside HTML tags: ``` C:\lp4e> python >>> from converters import Uppercase >>> >>> class HTMLize: ...
def write(self, line): ...
print('<PRE>%s</PRE>' % line.rstrip()) ... >>> Uppercase(open('spam.txt'), HTMLize()).process() <PRE>SPAM</PRE> <PRE>SPAM</PRE> <PRE>SPAM!</PRE> ``` **|** ----- If you trace through this example’s control flow, you’ll see that we get both uppercase conversion (by inheritance) and HTML formatting (by compo...
The processing code only cares that writers have a write method and that a method named convert is defined; it doesn’t care what those methods do when they are called. Such polymorphism and encapsulation of logic is behind much of the power of classes. As is, the `Processor superclass only provides a file-scanning loo...
In more realistic` work, we might extend it to support additional programming tools for its subclasses, and, in the process, turn it into a full-blown framework.
Coding such a tool once in a superclass enables you to reuse it in all of your programs.
Even in this simple example, because so much is packaged and inherited with classes, all we had to code was the HTML formatting step; the rest was free. For another example of composition at work, see exercise 9 at the end of Chapter 31 and its solution in Appendix B; it’s similar to the pizza shop example.
We’ve focused on inheritance in this book because that is the main tool that the Python language itself provides for OOP.
But, in practice, composition is used as much as inheritance as a way to structure classes, especially in larger systems.
As we’ve seen, inheritance and composition are often complementary (and sometimes alternative) techniques.
Because composition is a design issue outside the scope of the Python language and this book, though, I’ll defer to other resources for more on this topic. ###### Why You Will Care: Classes and Persistence I’ve mentioned Python’s pickle and shelve object persistence support a few times in this part of the book becaus...
In fact, these tools are often compelling enough to motivate the use of classes in general—by picking or shelving a class instance, we get data storage that contains both data and logic combined. For example, besides allowing us to simulate real-world interactions, the pizza shop classes developed in this chapter coul...
Instances of classes can be stored away on disk in a single step using Python’s ``` pickle or shelve modules.
We used shelves to store instances of classes in the OOP ``` tutorial in Chapter 27, but the object pickling interface is remarkably easy to use as well: ``` import pickle object = someClass() file = open(filename, 'wb') # Create external file pickle.dump(object, file) # Save object in file ...
The controllers can take care of administrative activities, such as keeping track of accesses and so on.
In Python, delegation is often implemented with the __getattr__ method hook; because it intercepts accesses to nonexistent attributes, a wrapper class (sometimes called a proxy class) can use `__getattr__ to route arbitrary accesses to a wrapped object.
The wrapper class` retains the interface of the wrapped object and may add additional operations of its own. **|** ----- Consider the file trace.py, for instance: ``` class wrapper: def __init__(self, object): self.wrapped = object # Save object def __getattr__(self, attrname): print(...
This code makes use of the getattr built-in function to fetch an attribute from the wrapped object by name string—getattr(X,N) is like X.N, except that N is an expression that evaluates to a string at runtime, not a variable.
In fact, getattr(X,N) is similar to X.__dict__[N], but the former also performs an inheritance search, like X.N, while the latter does not (see “Namespace Dictionaries” on page 696 for more on the __dict__ attribute). You can use the approach of this module’s wrapper class to manage access to any object with attribute...
Here, the wrapper class simply prints a trace message on each attribute access and delegates the attribute request to the embedded wrapped object: ``` >>> from trace import wrapper ``` `>>> x = wrapper([1,2,3])` _# Wrap a list_ `>>> x.append(4)` _# Delegate to list method_ ``` Trace: append ``` `>>> x.wrapped` _#...
We can use this to log our method calls, route method calls to extra or custom logic, and so on. We’ll revive the notions of wrapped objects and delegated operations as one way to extend built-in types in Chapter 31.
If you are interested in the delegation design pattern, also watch for the discussions in Chapters 31 and 38 of function decorators, a strongly related concept designed to augment a specific function or method call rather than the entire interface of an object, and class decorators, which serve as a way to automaticall...
Printing a wrapped object directly, for example, calls this method for __repr__ or __str__, which then passes the call on to the wrapped object.
In Python 3.0, this no longer happens: printing does not trigger __getattr__, and a default display is used instead.
In 3.0, new-style classes look up operator overloading methods in classes and skip the normal instance lookup entirely.
We’ll return to this issue in Chapter 37, in the context of managed attributes; for now, keep in mind that you may need to redefine operator overloading methods in wrapper classes (either by hand, by tools, or by superclasses) if you want them to be intercepted in 3.0. ###### Pseudoprivate Class Attributes Besides la...
In Part V, we learned that every name assigned at the top level of a module file is exported. By default, the same holds for classes—data hiding is a convention, and clients may fetch or change any class or instance attribute they like.
In fact, attributes are all “public” and “virtual,” in C++ terms; they’re all accessible everywhere and are looked up dynamically at runtime.[*] That said, Python today does support the notion of name “mangling” (i.e., expansion) to localize some names in classes.
Mangled names are sometimes misleadingly called “private attributes,” but really this is just a way to localize a name to the class that created it—name mangling does not prevent access by code outside the class.
This feature is mostly intended to avoid namespace collisions in instances, not to restrict access to names in general; mangled names are therefore better called “pseudoprivate” than “private.” Pseudoprivate names are an advanced and entirely optional feature, and you probably won’t find them very useful until you sta...
In fact, they are not always used even when they probably should be—more commonly, Python programmers code internal names with a single underscore (e.g., _X), which is just an informal convention to let you know that a name shouldn’t be changed (it means nothing to Python itself). Because you may see this feature in o...
In Python, it’s even possible to change or completely delete a class method at runtime. On the other hand, almost nobody ever does this in practical programs.
As a scripting language, Python is more about enabling than restricting.
Also, recall from our discussion of operator overloading in Chapter 29 that __getattr__ and __setattr__ can be used to emulate privacy, but are generally not used for this purpose in practice.
More on this when we code a more realistic privacy decorator Chapter 38. **|** ----- ###### Name Mangling Overview Here’s how name mangling works: names inside a class statement that start with two underscores but don’t end with two underscores are automatically expanded to include the name of the enclosing class.
For instance, a name like __X within a class named ``` Spam is changed to _Spam__X automatically: the original name is prefixed with a single ``` underscore and the enclosing class’s name.
Because the modified name contains the name of the enclosing class, it’s somewhat unique; it won’t clash with similar names created by other classes in a hierarchy. Name mangling happens only in class statements, and only for names that begin with two leading underscores.
However, it happens for every name preceded with double underscores—both class attributes (like method names) and instance attribute names assigned to `self attributes.
For example, in a class named` `Spam, a method named` ``` __meth is mangled to _Spam__meth, and an instance attribute reference self.__X is trans ``` formed to self._Spam__X.
Because more than one class may add attributes to an instance, this mangling helps avoid clashes—but we need to move on to an example to see how. ###### Why Use Pseudoprivate Attributes? One of the main problems that the pseudoprivate attribute feature is meant to alleviate has to do with the way instance attributes ...
In Python, all instance attributes wind up in the single instance object at the bottom of the class tree.
This is different from the C++ model, where each class gets its own space for data members it defines. Within a class method in Python, whenever a method assigns to a self attribute (e.g., ``` self.attr = value), it changes or creates an attribute in the instance (inheritance ``` searches happen only on reference, no...
Because this is true even if multiple classes in a hierarchy assign to the same attribute, collisions are possible. For example, suppose that when a programmer codes a class, she assumes that she owns the attribute name X in the instance.
In this class’s methods, the name is set, and later fetched: ``` class C1: def meth1(self): self.X = 88 # I assume X is mine def meth2(self): print(self.X) ``` Suppose further that another programmer, working in isolation, makes the same assumption in a class that he codes: ``` class C2: def metha(...
The problem arises if the two classes are ever mixed together in the same class tree: **|** ----- ``` class C3(C1, C2): ... I = C3() # Only 1 X in I! ``` Now, the value that each class gets back when it says self.X will depend on which class assigned it last.
Because all assignments to `self.X refer to the same single instance,` there is only one X attribute—I.X—no matter how many classes use that attribute name. To guarantee that an attribute belongs to the class that uses it, prefix the name with double underscores everywhere it is used in the class, as in this file, pri...
If you run a `dir call on` `I or inspect its` namespace dictionary after the attributes have been assigned, you’ll see the expanded names, _C1__X and _C2__X, but not X.
Because the expansion makes the names unique within the instance, the class coders can safely assume that they truly own any names that they prefix with two underscores: ``` % python private.py {'_C2__X': 99, '_C1__X': 88} 88 99 ``` This trick can avoid potential name collisions in the instance, but note that ...
If you know the name of the enclosing class, you can still access either of these attributes anywhere you have a reference to the instance by using the fully expanded name (e.g., I._C1__X = 77).
On the other hand, this feature makes it less likely that you will accidentally step on a class’s names. Pseudoprivate attributes are also useful in larger frameworks or tools, both to avoid introducing new method names that might accidentally hide definitions elsewhere in the class tree and to reduce the chance of in...
If a method is intended for use only within a class that may be mixed into other classes, the double underscore prefix ensures that the method won’t interfere with other names in the tree, especially in multiple-inheritance scenarios: ``` class Super: def method(self): ...
# A real application method class Tool: ``` **|** ----- ``` def __method(self): ...
# Becomes _Tool__method def other(self): self.__method() # Use my internal method class Sub1(Tool, Super): ... def actions(self): self.method() # Runs Super.method as expected class Sub2(Tool): def __init__(self): self.method = 99 # Doesn't break Tool.__method ``` We met multiple inheritance bri...
Recall that superclasses are searched according to their left-to-right order in class header lines. Here, this means Sub1 prefers Tool attributes to those in ``` Super.
Although in this example we could force Python to pick the application class’s ``` methods first by switching the order of the superclasses listed in the Sub1 class header, pseudoprivate attributes resolve the issue altogether.
Pseudoprivate names also prevent subclasses from accidentally redefining the internal method’s names, as in Sub2. Again, I should note that this feature tends to be of use primarily for larger, multiprogrammer projects, and then only for selected names.
Don’t be tempted to clutter your code unnecessarily; only use this feature for names that truly need to be controlled by a single class.
For simpler programs, it’s probably overkill. For more examples that make use of the `__X naming feature, see the` _lister.py_ mix-in classes introduced later in this chapter, in the section on multiple inheritance, as well as the discussion of `Private class decorators in` Chapter 38.
If you care about privacy in general, you might want to review the emulation of private instance attributes sketched in the section “Attribute Reference: __getattr__ and __setattr__” on page 718 in Chapter 29, and watch for the Private class decorator in Chapter 38 that we will base upon this special method.
Although it’s possible to emulate true access controls in Python classes, this is rarely done in practice, even for large systems. ###### Methods Are Objects: Bound or Unbound Methods in general, and bound methods in particular, simplify the implementation of many design goals in Python.
We met bound methods briefly while studying __call__ in Chapter 29.
The full story, which we’ll flesh out here, turns out to be more general and flexible than you might expect. In Chapter 19, we learned how functions can be processed as normal objects.
Methods are a kind of object too, and can be used generically in much the same way as other objects—they can be assigned, passed to functions, stored in data structures, and so on.
Because class methods can be accessed from an instance or a class, though, they actually come in two flavors in Python: **|** ----- _Unbound class method objects: no self_ Accessing a function attribute of a class by qualifying the class returns an unbound method object.
To call the method, you must provide an instance object explicitly as the first argument.
In Python 3.0, an unbound method is the same as a simple function and can be called though the class’s name; in 2.6 it’s a distinct type and cannot be called without providing an instance. _Bound instance method objects: self + function pairs_ Accessing a function attribute of a class by qualifying an instance returns ...
Python automatically packages the instance with the function in the bound method object, so you don’t need to pass an instance to call the method. Both kinds of methods are full-fledged objects; they can be transferred around a program at will, just like strings and numbers.
Both also require an instance in their first argument when run (i.e., a value for self).
This is why we had to pass in an instance explicitly when calling superclass methods from subclass methods in the previous chapter; technically, such calls produce unbound method objects. When calling a bound method object, Python provides an instance for you automatically—the instance used to create the bound method ...
This means that bound method objects are usually interchangeable with simple function objects, and makes them especially useful for interfaces originally written for functions (see the sidebar “Why You Will Care: Bound Methods and Callbacks” on page 756 for a realistic example). To illustrate, suppose we define the fo...
In fact, we can fetch a bound method without actually calling it. An object.name qualification is an object expression.
In the following, it returns a bound method object that packages the instance (object1) with the method function (Spam.doit).
We can assign this bound method pair to another name and then call it as though it were a simple function: ``` object1 = Spam() x = object1.doit # Bound method object: instance+function x('hello world') # Same effect as object1.doit('...') ``` **|** ----- On the other hand, if we qualify the class to ge...
To call this type of method, we must pass in an instance as the leftmost argument: ``` object1 = Spam() t = Spam.doit # Unbound method object (a function in 3.0: see ahead) t(object1, 'howdy') # Pass in instance (if the method expects one in 3.0) ``` By extension, the same rules apply within a class’s met...
A self.method expression is a bound method object because self is an instance object: ``` class Eggs: def m1(self, n): print(n) def m2(self): x = self.m1 # Another bound method object x(42) # Looks like a simple function Eggs().m2() # Prints 42 ``` Most of the time, you call ...
What we describe as an unbound method here is treated as a simple function in 3.0.
For most purposes, this makes no difference to your code; either way, an instance will be passed to a method’s first argument when it’s called through an instance. Programs that do explicit type testing might be impacted, though—if you print the type of an instance-less class method, it displays “unbound method” in 2....
When calling through a class, you must pass an instance manually only if the method expects one: ``` C:\misc> c:\python30\python >>> class Selfless: ``` † See the discussion of static and class methods in Chapter 31 for an optional exception to this rule.
Like bound methods, static methods can masquerade as basic functions because they do not expect instances when called. Python supports three kinds of class methods—instance, static, and class—and 3.0 allows simple functions in classes, too. **|** ----- ``` ...
def __init__(self, data): ... self.data = data ``` `... def selfless(arg1, arg2):` _# A simple function in 3.0_ ``` ... return arg1 + arg2 ``` `...