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.

Here, a tree of classic classes is emulating the search order of new-style classes: theassignment to the attribute in D picks the version in C, thereby subverting the normalinheritance search path (D.attr will be lowest in the tree). New-style classes can similarlyemulate classic classes by choosing the attribute above at the place where theclasses are mixed together:>>> class A(object): attr = 1 # New style>>> class B(A): pass>>> class C(A): attr = 2>>> class D(B,C): attr = B.attr # Choose A.attr, above>>> x = D( )>>> x.attr # Works like classic1If you are willing to always resolve conflicts like this, you can largely ignore thesearch order difference, and not rely on assumptions about what you meant whenyou coded your classes. Naturally, attributes picked this way can also be methodfunctions—methods are normal, assignable objects:>>> class A:... def meth(s): print 'A.meth'>>> class C(A):... def meth(s): print 'C.meth'>>> class B(A):... pass>>> class D(B,C): pass # Use default search order>>> x = D( ) # Will vary per class type>>> x.meth( ) # Defaults to classic orderA.meth>>> class D(B,C): meth = C.meth # Pick C's method: new style>>> x = D( )>>> x.meth( )C.meth>>> class D(B,C): meth = B.meth # Pick B's method: classic>>> x = D( )>>> x.meth( )A.methHere, we select methods by explicitly assigning to names lower in the tree. We mightalso simply call the desired class explicitly; in practice, this pattern might be morecommon, especially for things like constructors:class D(B,C):def meth(self):...C.meth(self)# Redefine lower# Pick C's method by callingSuch selections by assignment or call at mix-in points can effectively insulate yourcode from this difference in class flavors. Explicitly resolving the conflicts this way548 | Chapter 26: Advanced Class Topics

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

Saved successfully!

Ooh no, something went wrong!