04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

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

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

174 CHAPTER 9 ■ MAGIC METHODS, PROPERTIES, AND ITERATORS<br />

class NewStyle(object):<br />

more_code_here<br />

class OldStyle:<br />

more_code_here<br />

Of these two, NewStyle is a new-style class, while OldStyle is an old-style class.<br />

■Note Rather than subclass a built-in type, you can make sure you’re using the same metaclass as they<br />

do. Metaclasses are the classes of other classes (or types)—a rather advanced topic. However, you can use<br />

the built-in metaclass called type to create new-style classes rather easily. Either you put the following<br />

assignment in the top-level scope of your module (close to the top), or in the class-scope of your class:<br />

__metaclass__ = type<br />

Putting it at the beginning of a module makes it easy to make all your classes new-style. For more information<br />

on metaclasses, you can take a look at the (somewhat technical) article called “Unifying types and classes in<br />

Python 2.2” by Guido van Rossum (http://python.org/2.2/descrintro.html), or you can do a Web<br />

search for the term “python metaclasses.”<br />

In this book, I have taken the conservative approach of subclassing object only where it is<br />

needed (because object did not exist before version 2.2), but if you do not specifically have to<br />

make your programs compatible with old versions of Python, I would advise you to make all<br />

your classes new-style, and consistently use features such as the super function (described in<br />

the section “Using the super Function,” later in this chapter).<br />

Constructors<br />

The first magic method we’ll take a look at is the constructor. In case you have never heard the<br />

word “constructor” before, it’s basically a fancy name for the kind of initializing method I have<br />

already used in some of the examples, under the name init. What separates constructors from<br />

ordinary methods, however, is that the constructors are called automatically right after an object<br />

has been created. Thus, instead of doing what I’ve been doing up until now:<br />

>>> f = FooBar()<br />

>>> f.init()<br />

constructors make it possible to simply do this:<br />

>>> f = FooBar()<br />

Creating constructors in Python is really easy; simply change the init method’s name<br />

from the plain old init to the magic version, __init__:

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

Saved successfully!

Ooh no, something went wrong!