[Tutor] when to use properties?
John Ridley
ojokimu at yahoo.co.uk
Wed Apr 13 03:16:57 CEST 2005
--- Marcus Goldfish <magoldfish at gmail.com> wrote:
> Are there guidelines for when properties should be used vs. instance
> variables? For example, it often seems more convenient to directly
> use instance variables instead of properties, like MyClass2 listed
> below. Is one class more pythonic than the other?
Hello Marcus
One guideline for using properties is to simply ask yourself: do I need
to run other code when getting, setting or deleting this attribute?
Here's a demo of what I mean, based on your first example class:
>>> class MyClass1(object):
... def __init__(self, value=0):
... self.__value = value
... def getValue(self):
... # log attribute usage
... print repr(self),': value accessed'
... return self.__value
... def setValue(self, value):
... # validate new values
... if not isinstance(value, int) or value < 0:
... raise ValueError, 'positive integer required'
... self.__value = value
... def delValue(self):
... # reset to 0, instead of deleting
... self.__value = 0
... value = property(getValue, setValue, delValue)
...
>>> c = MyClass1()
>>> c.value = -1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 11, in setValue
ValueError: positive integer required
>>> c.value = 9
>>> print c.value
<__main__.MyClass1 object at 0x402b6c6c> :value accessed
9
>>> del c.value
>>> v = c.value
<__main__.MyClass1 object at 0x402b6c6c> : value accessed
>>> print v
0
>>>
Note that you could also do all of this by calling the methods
directly. For example, you could set the value to 1 by calling
self.setValue(1) or delete it by calling self.delValue(). The nice
thing about using properties, though, is that everything is accessed
through a single attribute name. So if there are lots of attributes
which need special get/set/del handling, you'll end up with much
cleaner code.
As to which way of doing things is the most pythonic: well, as always,
it depends on what you are trying to achieve - if your code is not
doing what you want it to do, then that is about as unpythonic as it
can get :-)
HTH
John Ridley
Send instant messages to your online friends http://uk.messenger.yahoo.com
More information about the Tutor
mailing list