How to write Smart Python programs?

Fredrik Lundh fredrik at pythonware.com
Wed Oct 11 15:33:10 CEST 2006


Antoine De Groote wrote:

> Don't forget to derive your class from object, otherwise properties
> won't work.

getters work, setters don't (because the old-style objects checks the instance
before it looks for hooks in the class):

>>> class Spam:
...     def getx(self):
...             return "x"
...     def setx(self, value):
...             print "set to", value
...     x = property(getx, setx)
...
>>> s = Spam()
>>> s.x
'x'
>>> s.x = "y"
>>> s.x
'y'

>> As a side node, the getters/setters of a property are often either
>> marked as implementation (the _leading_underscore convention) or deleted
>> from the class's dict once the property is created or 'masked' one way
>> or another so they don't pollute the class's namespace.
>
> You mean like manually removed from the dict?

explicitly deleted:

>>> class Spam(object):
...     def getx(self):
...             return "x"
...     def setx(self, value):
...             print "set to", value
...     x = property(getx, setx)
...     del getx, setx
...
>>> s = Spam()
>>> s.x
'x'
>>> s.x = "y"
set to y
>>> s.getx()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Spam' object has no attribute 'getx'

(note that the class definition is executed in a class-specific namespace; whatever's
left in that namespace when you reach the end of the class statement is added to the
class).

</F> 






More information about the Python-list mailing list