15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

If we try it out, we see that it saves the first value we give it but does not allow us to set it again:<br />

>>> inst = ProtectAndHideX('foo')<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

File "prop.py", line 5, in __init__<br />

assert isinstance(x, int), \<br />

AssertionError: "x" must be an integer!<br />

>>> inst = ProtectAndHideX(10)<br />

>>> print 'inst.x =', inst.x<br />

inst.x = 10<br />

>>> inst.x = 20<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

AttributeError: can't set attribute<br />

Here is another example, but with a setter:<br />

class HideX(object):<br />

def __init__(self, x):<br />

self.x = x<br />

def get_x(self):<br />

return ~self.__x<br />

def set_x(self, x):<br />

assert isinstance(x, int), \<br />

'"x" must be an integer!'<br />

self.__x = ~x<br />

x = property(get_x, set_x)<br />

Here is the output of this example:<br />

>>> inst = HideX(20)<br />

>>> print inst.x<br />

20<br />

>>> inst.x = 30<br />

>>> print inst.x<br />

30<br />

This property works because by the time the constructor is called to set the initial value of x, the getter<br />

already saves it as ~x to self.__x.<br />

You can even stick in a documentation string for your attribute, as shown here in this next example:<br />

from math import pi<br />

def get_pi(dummy):<br />

return pi

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

Saved successfully!

Ooh no, something went wrong!