12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

if __name__ == "_ _main_ _":X = Sub( )print X# Mixed-in reprHere, Sub inherits names from both Super and Lister; it’s a composite of its ownnames and names in both its superclasses. When you make a Sub instance and printit, you automatically get the custom representation mixed in from Lister:C:\lp3e> python testmixin.pyLister works in any class it’s mixed into because self refers to an instance of thesubclass that pulls Lister in, whatever that may be. If you later decide to extendLister’s _ _repr_ _ to also print all the class attributes that an instance inherits,you’re safe; because it’s an inherited method, changing Lister._ _repr_ _ automaticallyupdates the display of each subclass that imports the class and mixes it in. *In a sense, mix-in classes are the class equivalent of modules—packages of methodsuseful in a variety of clients. Here is Lister working again in single-inheritance modeon a different class’s instances:>>> from mytools import Lister>>> class x(Lister):... pass...>>> t = x( )>>> t.a = 1; t.b = 2; t.c = 3>>> tOOP is all about code reuse, and mix-in classes are a powerful tool. Like almost everythingelse in programming, multiple inheritance can be a useful device when appliedwell; however, in practice, it is an advanced feature and can become complicated ifused carelessly or excessively. We’ll revisit this topic as a gotcha at the end of the nextchapter. In that chapter, we’ll also meet an option (new-style classes) that modifies thesearch order for one special multiple inheritance case.* If you’re curious how, flip back to “Namespace Dictionaries” in Chapter 24 for hints. We saw there that eachclass has a built-in attribute called _ _bases_ _, which is a tuple of the class’ superclass objects. A general-purposeclass hierarchy lister or browser can traverse the inheritance tree from an instance’s _ _class_ _ to itsclass, and then from the class’ _ _bases_ _ to all superclasses recursively, much like the classtree.py exampleshown earlier. In <strong>Python</strong> 2.2 and later, it’s even simpler, as the built-in dir function now includes inheritedattribute names automatically. If you don’t care about displaying the tree structure, you can just scan the dirlist instead of the dictionary keys list, and use getattr to fetch attributes by name string instead of dictionarykeyindexing. We’ll rehash this idea in one of this part’s closing exercises.Multiple Inheritance | 531

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

Saved successfully!

Ooh no, something went wrong!