Adding properties to objects

Shalabh Chaturvedi shalabh at cafepy.com
Tue Apr 13 21:55:42 EDT 2004


Matthew Barnes wrote:
> matthew at barnes.net (Matthew Barnes) wrote:
> 
>>Is it possible to add properties to objects dynamically?

You can add properties dynamically, but to the type (i.e. 'class') and 
not the instance (i.e. 'object'). For your example:

 >>> x = Foo()
 >>> def f(a,b=None): # a bogus getter, setter, deleter
...     print a,b
...
 >>> Foo.property = property(f,f,f)
 >>> x.property
<__main__.Foo object at 0x008F3CB0> None
 >>> x.property = 1
<__main__.Foo object at 0x008F3CB0> 1
 >>> del x.property
<__main__.Foo object at 0x008F3CB0> None
 >>>

This property will work for *all* instances of Foo.

> 
> So the impression I'm getting is that it's *possible* but not really
> intended, otherwise there would be better support in the core
> language.  Fair statement?

I don't see any reason why dynamically adding properties to the *type* 
is not intended. It's not complicated and works fine.

> I'll take that as a clue that there's probably a cleaner approach to
> the problem I'm trying to solve.

What is the problem you are trying to solve?

> The feedback was informative... thank you all!
>
> Matthew Barnes

HTH,
Shalabh





More information about the Python-list mailing list