16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

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.

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

class FooBar:<br />

def __init__(self):<br />

self.somevar = 42<br />

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

>>> f.somevar<br />

42<br />

Now, that’s pretty nice. But you may wonder what happens if you give the construc<strong>to</strong>r<br />

some parameters <strong>to</strong> work with. Consider the following:<br />

class FooBar:<br />

def __init__(self, value=42):<br />

self.somevar = value<br />

How do you think you could use this? Because the parameter is optional, you certainly<br />

could go on like nothing had happened. But what if you wanted <strong>to</strong> use it (or you hadn’t made<br />

it optional)? I’m sure you’ve guessed it, but let me show you anyway:<br />

>>> f = FooBar('This is a construc<strong>to</strong>r argument')<br />

>>> f.somevar<br />

'This is a construc<strong>to</strong>r argument'<br />

Of all the magic methods in <strong>Python</strong>, __init__ is quite certainly the one you’ll be using<br />

the most.<br />

■Note <strong>Python</strong> has a magic method called __del__, also known as the destruc<strong>to</strong>r. It is called just before<br />

the object is destroyed (garbage collected), but because you cannot really know when (or if) this happens,<br />

I would advise you <strong>to</strong> stay away from __del__ if at all possible.<br />

Overriding the Construc<strong>to</strong>r<br />

In Chapter 7, you learned about inheritance. Each class may have one or more superclasses,<br />

from which they inherit behavior. If a method is called (or an attribute is accessed) on an<br />

instance of class B and it is not found, its superclass A would be searched. Consider the following<br />

two classes:<br />

class A:<br />

def hello(self):<br />

print "Hello, I'm A."<br />

class B(A):<br />

pass

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

Saved successfully!

Ooh no, something went wrong!