15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

(, , , , , )<br />

*MRO Problems Caused by Diamonds<br />

The classic class method resolution never gave folks too many problems. It was simple to explain and<br />

easy to understand. Most classes were single inheritance, and multiple inheritance was usually limited to<br />

mixing two completely discrete classes together. This is where the term mix-in classes (or "mix-ins")<br />

comes from.<br />

Why the Classic Classes MRO Fails<br />

The unification of types and classes in 2.2 brought about a new "problem," and that is related to all<br />

(root) classes inheriting from object, the mother of all types. The diagram of a simple multiple<br />

inheritance hierarchy now formed a diamond. Taking some inspiration from Guido van Rossum's essay,<br />

let us say that you have classic classes B and C, as defined below where C overrides its constructor but<br />

B does not, and D inherits from both B and C:<br />

class B:<br />

pass<br />

class C:<br />

def __init__(self):<br />

print "the default constructor"<br />

class D(B, C):<br />

pass<br />

When we instantiate D, we get:<br />

>>> d = D()<br />

the default constructor<br />

Figure 13-3 illustrates the class hierarchy for B, C, and D, as well as the problem introduced when we<br />

change the code to use new-style classes:<br />

Figure 13-3. Inheritance problems are caused by the appearance of the base<br />

class required by new-style classes, forming a diamond shape in the<br />

inheritance hierarchy. An instance of D should not miss an upcall to C nor<br />

should it upcall to A twice (since both B and C derive from A). Be sure to read<br />

the "Cooperative Methods" section of Guido van Rossum's essay for further<br />

clarification.

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

Saved successfully!

Ooh no, something went wrong!