adding properties dynamically (how to?)

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Aug 20 05:11:29 EDT 2008


Rafe a écrit :
(snip)
> 
> You can dynamically add properties to a class

The OP was asking for *per instance* properties...

> 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


Very bad idea IMHO. __new__ is called on each instanciation, which means 
the above code will uselessly modify the class each time you create an 
instance of it, overwriting the same properties again and again and 
again. If what you want is to automagically add properties (or whatever 
type of attributes) to a class and/or it's subclass, you'd be better 
using a custom metaclass.






More information about the Python-list mailing list