By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,737 Members | 1,335 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,737 IT Pros & Developers. It's quick & easy.

is it possible to add a property to an instance?

P: n/a
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.

Thanks,
Darren
Jul 22 '08 #1
Share this Question
Share on Google+
3 Replies

P: n/a
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:
class Base(object):

def x_get(self):
return self.x_get_overload()

x = property(x_get)
a = Base()

def foo(self):
return "something"

a.x_get_overload = new.instancemethod(foo)

Diez
Jul 22 '08 #2

P: n/a
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.
yes. You need nothing special, just add it:

class fish(object):
pass

a=fish()
a.legs=4
print a.legs

(or print (a.legs) on Python 3.0 and above)

so you add a property to an instance and proove that Darwin was right
in one go.

Harald
Jul 22 '08 #3

P: n/a
GHUM 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.

yes. You need nothing special, just add it:

class fish(object):
pass

a=fish()
a.legs=4
print a.legs
Sorry, that's an attribute, not a property.

Jul 22 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.