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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

Initialize the arithmetic sequence.<br />

start - the first value in the sequence<br />

step - the difference between two adjacent values<br />

changed - a dictionary of values that have been modified by<br />

the user<br />

"""<br />

self.start = start<br />

# S<strong>to</strong>re the start value<br />

self.step = step<br />

# S<strong>to</strong>re the step value<br />

self.changed = {}<br />

# No items have been modified<br />

def __getitem__(self, key):<br />

"""<br />

Get an item from the arithmetic sequence.<br />

"""<br />

checkIndex(key)<br />

try: return self.changed[key]<br />

except KeyError:<br />

return self.start + key*self.step<br />

# Modified?<br />

# otherwise...<br />

# ...calculate the value<br />

def __setitem__(self, key, value):<br />

"""<br />

Change an item in the arithmetic sequence.<br />

"""<br />

checkIndex(key)<br />

self.changed[key] = value<br />

# S<strong>to</strong>re the changed value<br />

This implements an arithmetic sequence, a sequence of numbers in which each is greater<br />

than the previous one by a constant amount. The first value is given by the construc<strong>to</strong>r parameter<br />

start (defaulting <strong>to</strong> zero), while the step between the values is given by step (defaulting <strong>to</strong> one).<br />

You allow the user <strong>to</strong> change some of the elements by s<strong>to</strong>ring the exceptions <strong>to</strong> the general rule in<br />

a dictionary called changed. If the element hasn’t been changed, it is calculated as start+key*step.<br />

Here is an example of how you can use this class:<br />

>>> s = ArithmeticSequence(1, 2)<br />

>>> s[4]<br />

9<br />

>>> s[4] = 2<br />

>>> s[4]<br />

2<br />

>>> s[5]<br />

11<br />

Note that it is illegal <strong>to</strong> delete items, which is why I haven’t implemented __del__:

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

Saved successfully!

Ooh no, something went wrong!