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.

in which we list them in the class header won’t help—we will have to override inheritanceby manually assigning to the attribute name in the Sub class:class Lister:def _ _repr_ _(self): ...def other(self): ...class Super:def _ _repr_ _(self): ...def other(self): ...class Sub(Lister, Super):other = Super.otherdef _ _init_ _(self):...# Get Lister's _ _repr_ _ by listing it first# But explicitly pick Super's version of otherx = Sub( )# Inheritance searches Sub before Super/ListerHere, the assignment to other within the Sub class creates Sub.other—a referenceback to the Super.other object. Because it is lower in the tree, Sub.other effectivelyhides Lister.other, the attribute that the inheritance search would normally find.Similarly, if we listed Super first in the class header to pick up its other, we wouldneed to select Lister’s method explicitly:class Sub(Super, Lister):_ _repr_ _ = Lister._ _repr_ _# Get Super's other by order# Explicitly pick Lister._ _repr_ _Multiple inheritance is an advanced tool. Even if you understood the last paragraph,it’s still a good idea to use it sparingly and carefully. Otherwise, the meaning of aname may come to depend on the order in which classes are mixed in an arbitrarilyfar-removed subclass. (For another example of the technique shown here in action,see the discussion of explicit conflict resolution in “New-Style Classes” earlier in thischapter.)As a rule of thumb, multiple inheritance works best when your mix-in classes are asself-contained as possible—because they may be used in a variety of contexts, theyshould not make assumptions about names related to other classes in a tree. Thepseudoprivate attributes feature we studied earlier can help by localizing names thata class relies on owning, and limiting the names that your mix-in classes add to themix. In this example, for instance, if Lister only means to export its custom _ _repr_ _,it can name its other method _ _other to avoid clashing with other classes.Methods, Classes, and Nested ScopesThis gotcha went away in <strong>Python</strong> 2.2, with the introduction of nested functionscopes, but I’ve retained it here for historical perspective, for readers working witholder <strong>Python</strong> releases, and because it demonstrates what happens to the new nestedfunction scope rules when one layer of the nesting is a class.Class Gotchas | 561

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

Saved successfully!

Ooh no, something went wrong!