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.

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

adding the necessary behavior of initializing the counter attribute (in __init__) and updating<br />

the counter attribute (in __getitem__).<br />

■Note Overriding __getitem__ is not a bullet-proof way of trapping user access because there are other<br />

ways of accessing the list contents, such as through the pop method.<br />

Here is an example of how CounterList may be used:<br />

>>> cl = CounterList(range(10))<br />

>>> cl<br />

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]<br />

>>> cl.reverse()<br />

>>> cl<br />

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]<br />

>>> del cl[3:6]<br />

>>> cl<br />

[9, 8, 7, 3, 2, 1, 0]<br />

>>> cl.counter<br />

0<br />

>>> cl[4] + cl[2]<br />

9<br />

>>> cl.counter<br />

2<br />

As you can see, CounterList works just like list in most respects. However, it has a counter<br />

attribute (initially zero), which is incremented each time you access a list element. After performing<br />

the addition cl[4] + cl[2], the counter has been incremented twice, <strong>to</strong> the value 2.<br />

More Magic<br />

There are special (magic) names for many purposes—what I’ve shown you so far is just a small<br />

taste of what is possible. Most of the magic methods available are meant for fairly advanced<br />

use, so I won’t go in<strong>to</strong> detail here. However, if you are interested, it is possible <strong>to</strong> emulate numbers,<br />

make objects that can be called as if they were functions, influence how objects are compared,<br />

and much more. For more information on which magic methods are available, see the section<br />

“Special Method Names” in the <strong>Python</strong> Reference Manual (http://www.python.org/doc/ref/<br />

specialnames.html).<br />

Properties<br />

In Chapter 7, I mentioned accessor methods. Accessors are simply methods with names such<br />

as getHeight and setHeight and are used <strong>to</strong> retrieve or rebind some attribute (which may be

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

Saved successfully!

Ooh no, something went wrong!