Property error

George Sakkis george.sakkis at gmail.com
Fri Dec 15 10:46:32 EST 2006


king kikapu wrote:

> Your example Dennis, work as expected. I understand the mistake i have
> made. But when i try to fix the original code usihn @property now, it
> gives me the same error.
> So, here it is:
>
> class Person(object):
>     _age = 0
>
>     @property
>     def age():
>         def fget(self):
>             return self._age
>         def fset(self, value):
>             self._age = value
>
> me = Person()
> me.age = 34
> print me.age
>
>
> I am sure it is something very obvious but my skills does not (yet)
> enable me to figure this out,,,

As others have already replied, the default property doesn't work this
way. In your example, it is possible to write it in one line using
lambda:

class Person(object):

    age = property(fget=lambda self: self._age,
                   fset=lambda self, value: setattr(self,'_age',value))

If any of fget,fset,fdel cannot be written as lambda or you'd rather
write them as functions, you may use the recipe at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698.

HTH,
George




More information about the Python-list mailing list