is it possible to add a property to an instance?
Diez B. Roggisch
deets at nospam.web.de
Tue Jul 22 14:51:30 CEST 2008
Darren Dale wrote:
> Does anyone know if it is possible to add a property to an instance at
> runtime? I didn't see anything about it in the standard library's new
> module, google hasn't turned up much either.
Depending on what you *really* want - yes or no.
It is *not* possible to have a property *only* on one instance, because
properties rely on the descriptor-protocol being used, and that only works
for class-attributes. So it's not a matter of "only" adding
a = Foo()
a.something = property(...)
However, you can of course try & come up with a scheme that only invokes
getters and setters if defined, and otherwise returns a
default-value/raises an attribute-error. Roughly like this:
x = property(x_get)
a = Base()
a.x_get_overload = new.instancemethod(foo)
More information about the Python-list