change property after inheritance

Maric Michaud maric at
Fri Sep 8 11:42:20 CEST 2006

Le jeudi 07 septembre 2006 15:33, Steven Bethard a écrit :
> Well, lambda's not going away[1],

Sure, they won't.

> but there's no *need* for lambda here. 
>   It could be written as::

Le jeudi 07 septembre 2006 17:16, George Sakkis a écrit :
> Sure, it *could*; whether it *should* is a different issue. I can't
> imagine a case for absolute *need* of lambda, but there are several
> cases where it is probably the best way, such as the one of this
> thread.

I have no preferences here, I used lambdas because it's more compact but they 
have also their drawback, when the function get a little more complex the 
code is quickly confusing. The main advantage of the lambdas in this case is 
to not pollute the class namespace.

Le jeudi 07 septembre 2006 23:48, Steven Bethard a écrit :
>  Try using one of the following recipies:

The code i wrote was to demonstrate late binding is usually not needed (and 
it's not the semantic of properties so it's a bit like "make Java in 
Only the second recipe has to do with it, but is not clean IMHO, it's 
unnecessary complicated and it introduce a extra level of indentation which 
is rather confusing, the 'self' variable in accessors is not what it seems to 
be. Moreover, it introduce a new semantic for a functionality which is 
already part of the language, what's the goal ? To lost python developers 
reading your code ?

If you really want late binding, the first recipe may be a solution, but it 
should be both simpler and should not introduce a new semantic (the functions 
passed as strings is disappointing).
I'd write it like this :

class LateBindingProperty(property) :
    __doc__ = property.__dict__['__doc__'] # see bug #576990

    def __init__(self, fget=None, fset=None, fdel=None, doc=None) :
        if fget : fget = lambda s, n=fget.__name__ : getattr(s, n)()
        if fset : fset = lambda s, v, n=fset.__name__ : getattr(s, n)(v)
        if fdel : fdel = lambda s, n=fdel.__name__ : getattr(s, n)()
        property.__init__(self, fget, fset, fdel, doc)

In [4]: class A(object) :
   ...:     def getx(self) : return self._x
   ...:     def setx(self, v) : self._x = v
   ...:     p=LateBindingProperty(getx, setx)

In [5]: class B(A) :
   ...:     def setx(self, v) : A.setx(self, 2*v)

In [8]: a=A()

In [9]: a.p = 5

In [10]: a.p
Out[10]: 5

In [11]: a._x
Out[11]: 5

In [12]: b=B()

In [13]: b.p=5

In [14]: b.p
Out[14]: 10


Maric Michaud

Aristote -
3 place des tapis
69004 Lyon
Tel: +33 426 880 097

More information about the Python-list mailing list