12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

attributes, a wrapper class (sometimes called a proxy class) can use _ _getattr_ _ toroute arbitrary accesses to a wrapped object. The wrapper class retains the interfaceof 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 = objectdef _ _getattr_ _(self, attrname):print 'Trace:', attrnamereturn getattr(self.wrapped, attrname)# Save object# Trace fetch# Delegate fetchRecall from Chapter 24 that _ _getattr_ _ gets the attribute name as a string. Thiscode makes use of the getattr built-in function to fetch an attribute from thewrapped object by name string—getattr(X,N) is like X.N, except that N is anexpression that evaluates to a string at runtime, not a variable. In fact, getattr(X,N) issimilar to X._ _dict_ _[N], but the former also performs an inheritance search, likeX.N, while the latter does not (see “Namespace Dictionaries” in Chapter 24 for moreon the _ _dict_ _ attribute).You can use the approach of this module’s wrapper class to manage access to anyobject with attributes—lists, dictionaries, and even classes and instances. Here, thewrapper class simply prints a trace message on each attribute access, and delegatesthe 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 methodTrace: append>>> x.wrapped # Print my member[1, 2, 3, 4]>>> x = wrapper({"a": 1, "b": 2}) # Wrap a dictionary>>> x.keys( ) # Delegate to dictionary methodTrace: keys['a', 'b']The net effect is to augment the entire interface of the wrapped object, with additionalcode in the wrapper class. We can use this to log our method calls, routemethod calls to extra or custom logic, and so on.We’ll revive the notions of wrapped objects and delegated operations as one way toextend built-in types in Chapter 26. If you are interested in the delegation design pattern,also watch for the discussion of function decorators in Chapter 26—this is astrongly related concept, designed to augment a specific function or method call,rather than the entire interface of an object.528 | Chapter 25: Designing with Classes

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!