Property error

Peter Otten __peter__ at web.de
Fri Dec 15 06:39:16 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,,,

@decorator
def f():
   # ...

is the same as

def f():
    # ...
f = decorator(f())

What happens when your age() function is invoked? There is no explicit
return statement, so None is implicitly returned, and

age = property(age())

is the same as age = property(None)

i. e. you get a property with None as the getter. What you want is

>>> def star_property(f):
...     return property(**f())
...
>>> class Person(object):
...     _age = "unknown"
...     @star_property
...     def age():
...             def fget(self):
...                     return self._age
...             def fset(self, value):
...                     self._age = value
...             return locals()
...
>>> person = Person()
>>> person.age
'unknown'
>>> person.age = 42
>>> person.age
42

However, that is rather hackish, and I recommend that you stick with the
standard approach given by Dennis and limit the use of property as a
decorator to read-only attributes:

>>> class Forever42(object):
...     @property
...     def age(self): return 42
...
>>> Forever42().age
42

Peter




More information about the Python-list mailing list