Minor annoyances with properties

Christian Heimes lists at cheimes.de
Fri May 28 05:50:56 EDT 2010


Am 28.05.2010 11:31, schrieb eb303:
> On May 27, 3:24 pm, Christian Heimes <li... at cheimes.de> wrote:
>>>  Do I miss something?
>>> Is this the way to do it, or is there a better one?
>>
>> A better way was introduced in Python 2.6. Seehttp://docs.python.org/library/functions.html?highlight=property#prop...
>> I have a Python only version around if you are still using Python 2.5.
>>
>> Christian
> 
> Mmmm, I might still miss something. OK, I can replace my initial
> property using @property and @p.setter, but it doesn't seem to work in
> subclasses:
> 
> class A(object):
>   @property
>   def p(self):
>     return self._p
>   @p.setter
>   def _set_p(self, p):
>     self._p = p
> class B(A):
>   @p.setter
>   def _set_p(self, p):
>> 
> results in:
> 
> Traceback (most recent call last):
>   File "toto.py", line 8, in <module>
>     class B(A):
>   File "toto.py", line 9, in B
>     @p.setter
> NameError: name 'p' is not defined

It doesn't work because "p" is not in the scope of B's body while B is
created. You have to write

class B(A):
    # access the "p" property from class A
    @A.p.setter
    def p(self, p):
        pass

    # once p is in the class body scope, you must not use A.p again
    @p.deleter
    def p(self):
        pass

Christian




More information about the Python-list mailing list