How to write Smart Python programs?

Bruno Desthuilliers onurb at xiludom.gro
Wed Oct 11 17:41:23 CEST 2006

Antoine De Groote wrote:
> Bruno Desthuilliers wrote:
>>> And what does property mean anyway? 
>> See above. A property is a computed attribute : you access it like a
>> 'data' attribute, but it really uses getters/setters. The point here is
>> that client code doesn't know nor need to know if it's a plain attribute
>> or a computed one. This let you change implementation (turn a plain
>> attribute into a computed one) without breaking the API. So the real
>> thing is not "don't use getters and setters", but "don't bother with
>> getters and setters, you'll be able to add them transparently if and
>> when needed".
> Ok great, now I understand. It's nice actually :-)
> For anyone else trying this for the first time, the following might be
> interesting, as I had trouble with this at first:
> Don't forget to derive your class from object, otherwise properties
> won't work.

FWIW, I don't see the point of still using old-style classes (apart for
compat with old Python versions...)

>> 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?


> Because (at least on the
> system I tried) it doesn't happen automatically. (Windwos XP, Python 2.5)

My usual idiom for properties is:

class MyClass(object):
  def propname():
    def fget(self): return self._something * 2
    def fset(self, value): self._something = int(value) / 2
    return property(**locals())

(Don't remember where it comes from...)

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list