15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

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

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

class B(object):<br />

pass<br />

class C(object):<br />

def __init__(self):<br />

print "the default constructor"<br />

Not much change here other than adding (object) to both class declarations, right? That is true, but as<br />

you can see in the diagram, the hierarchy is now a diamond; the real problem is in the MRO now. If we<br />

used the classic class MRO, when instantiating D, we no longer get C.__init__()... we get object.<br />

__init__()! This is the exact reason why the MRO needed to be changed.<br />

Although we saw that it does change the way attributes are looked up in our example above with the GC<br />

class, you do not have to worry about lots of code breaking. Classic classes will still use the old MRO<br />

while new-style classes will use its MRO. Again, if you do not need all of the features of the new-style<br />

classes, there is nothing wrong with continuing to develop using classic classes.<br />

Summary<br />

Classic classes have a depth-first MRO algorithm. Because new-style classes inherit from object, a new<br />

MRO had to be created because of problems ensuing from the now-diamond-shaped class hierarchy.<br />

You can read more about new-style classes, the MROs, and more in:<br />

● Guido van Rossum's essay on the unification of types and classes: http://www.python.org/<br />

download/releases/2.2.3/descrintro<br />

● PEP 252: Making Types Look More Like Classes http://www.python.org/doc/peps/pep-0252<br />

● "What's New in <strong>Python</strong> 2.2" document http://www.python.org/doc/2.2.3/whatsnew<br />

● <strong>Python</strong> 2.3 Method Resolution order paper http://python.org/download/releases/2.3/mro/

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

Saved successfully!

Ooh no, something went wrong!