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.

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

__metaclass__ = type<br />

class MyClass:<br />

@staticmethod<br />

def smeth():<br />

print 'This is a static method'<br />

@classmethod<br />

def cmeth(cls):<br />

print 'This is a class method of', cls<br />

Once you’ve defined these methods, they can be used like this (that is, without instantiating<br />

the class):<br />

>>> MyClass.smeth()<br />

This is a static method<br />

>>> MyClass.cmeth()<br />

This is a class method of <br />

Static methods and class methods haven’t historically been important in Python, mainly<br />

because you could always use functions or bound methods instead, in some way, but also because<br />

the support hasn’t really been there in earlier versions. So even though you may not see them<br />

used much in current code, they do have their uses (such as factory functions, if you’ve heard<br />

of those), and you may well think of some new ones.<br />

__getattr__, __setattr__, and Friends<br />

It is possible to implement properties with old-style classes, too, but you have to use magic<br />

methods rather than the property function. The following four methods provide all the functionality<br />

you need (in old-style classes, you only use the last three):<br />

__getattribute__(self, name): Automatically called when the attribute name is accessed.<br />

(Works correctly on new-style classes only.)<br />

__getattr__(self, name): Automatically called when the attribute name is accessed and<br />

the object has no such attribute.<br />

__setattr__(self, name, value): Automatically called when an attempt is made to bind<br />

the attribute name to value.<br />

__delattr__(self, name): Automatically called when an attempt is made to delete the<br />

attribute name.<br />

Although a bit trickier (and less efficient) to use than property, these magic methods are<br />

quite powerful because you can write code in one of these methods that deals with several<br />

properties. (If you have a choice, though, stick with property.)<br />

Here is the Rectangle example again, this time with magic methods:

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

Saved successfully!

Ooh no, something went wrong!