How to make a method into a property without using the @property decorator
Peter Otten
__peter__ at web.de
Sat Oct 23 11:01:56 EDT 2010
Phlip wrote:
> Pythonistas:
>
> Here's the property decorator:
>
> @property
> def foo(self): return 'bar'
>
> If I generate foo dynamically, how to I make it a property?
>
> setattr(self, 'foo', property(lambda: 'bar'))
>
> Variations of that are apparently not working.
You have to put the property descriptor into the class, not an instance:
>>> class A(object):
... pass
...
>>> a = A()
>>> setattr(type(a), "foo", property(lambda self: "FOO"))
>>> a.foo
'FOO'
>>> A().foo
'FOO'
> (I'm heading for a proxy pattern, where if you never call the
> generated prop, you never hit the database to load it into memory.)
You may be better off with __getattr__().
Peter
More information about the Python-list
mailing list