Tricky Areas in Python

Alex Martelli aleaxit at yahoo.com
Mon Oct 24 11:09:12 EDT 2005


Steven D'Aprano <steve at REMOVEMEcyber.com.au> wrote:
   ...
> my hard-won ignorance, and admit that I don't see the 
> problem with the property examples:
> 
> >     class Sic:
> >         def getFoo(self): ...
> >         def setFoo(self): ...
> >         foo = property(getFoo, setFoo)

Sorry for skipping the 2nd argument to setFoo, that was accidental in my
post.  The problem here is: class Sic is "classic" ("legacy",
"old-style") so property won't really work for it (the setter will NOT
trigger when you assign to s.foo and s is an instance of Sic).

> > to
> >     class Base(object)
> >         def getFoo(self): ...
> >         def setFoo(self): ...
> >         foo = property(getFoo, setFoo)
> > 
> >     class Derived(Base):
> >         def getFoo(self): ....
> 
> Unless the answer is "Why are you using setters and 
> getters anyway? This isn't Java you know."

Nope, that's not a problem -- presumably the "..." bodies DO something
useful, and they do get nicely dressed in attribute syntax.  The
problem, as others have indicated, is that overriding doesn't work as
one might expect -- the solution, in Python 2.4 and earlier, is to use
one extra level of indirection:
    def __getFoo(self): return self.getFoo()
    def getFoo(self): ...
    foo = property(__getFoo)
so the name lookup for 'getFoo' on self happens when you access s.foo
(for s being an instance of this here-sketched class) and overriding
works just as expected.  This can be seen as the simplest possible use
case for the "Template Method" Design Pattern, btw;-)


Alex



More information about the Python-list mailing list