how to add property "dynamically"?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Aug 20 02:38:11 EDT 2008


En Tue, 19 Aug 2008 15:02:29 -0300, Rafe <rafesacks at gmail.com> escribió:

> On Aug 17, 5:09 pm, Bruno Desthuilliers
> <bdesth.quelquech... at free.quelquepart.fr> wrote:
>> akonsu a écrit :> hello,
>>
>> > i need to add properties to instances  dynamically during run time.
>>
>> Properties must be class attributes. The only way (the only way I know)
>> to get them to work as instance-attributes is to overload
>> __getattribute__, which is tricky and may have pretty bad impact on
>> lookup perfs - and ruins the whole point of using properties FWIW.
>
> You can dynamically add properties (or anything else) to a CLASS just
> before returning the
> instance using __new__():
>
> class AClass(object):
>     def __new__(cls):
>         setattr(cls,"propName", property(fget = ...,
>                                          fset = ...,
>                                          fdel = ...,
>                                          doc  = ...) )
>
>         obj = super(AClass, cls).__new__(cls)
>         return obj

If you modify the class, this makes the property available to all existing  
instances, not just the one being created. Any previous property of the  
same name is overriden too.

-- 
Gabriel Genellina




More information about the Python-list mailing list