is it possible to add a property to an instance?

D

Darren Dale

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
 
D

Diez B. Roggisch

Darren said:
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
 
G

GHUM

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
 
D

Darren Dale

GHUM said:
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.
 
A

Alan Isaac

Darren Dale wrote to GHUM:
Sorry, that's an attribute, not a property.


This is a question about terminology.
In contrast to Darren's recommended usage,
I have run into the following.

If hasattr(x,'a') is True, for instance object `x`,
then `a` is an attribute of `x`.
Attributes are data attributes or callable attributes.
Data attributes are variables or properties.
Callable attributes are usually method attributes.

This seemed about right to me, but a better
(or "official") taxonomy would be welcome.

Thanks,
Alan Isaac
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top