how to add property "dynamically"?

Larry Bates larry.bates at websafe.com`
Sun Aug 17 02:01:21 EDT 2008


akonsu wrote:
> hello,
> 
> i need to add properties to instances dynamically during run time.
> this is because their names are determined by the database contents.
> so far i found a way to add methods on demand:
> 
> class A(object) :
>     def __getattr__(self, name) :
>         if name == 'test' :
>             def f() : return 'test'
>             setattr(self, name, f)
>             return f
>         else :
>             raise AttributeError("'%s' object has no attribute '%s'" %
> (self.__class__.__name__, name))
> 
> this seems to work and i can invoke method test() on an object. it
> would be nice to have it as property though. so i tried:
> 
> class A(object) :
>     def __getattr__(self, name) :
>         if name == 'test' :
>             def f() : return 'test'
>             setattr(self, name, property(f))
>             return f
>         else :
>             raise AttributeError("'%s' object has no attribute '%s'" %
> (self.__class__.__name__, name))
> 
> but this does not work, instance.test returns a callable but does not
> call it.
> 
> i am not an expert in python, would someone please tell me what i am
> doing wrong?
> 
> thanks
> konstantin

Are you sure you can't get by by adding attributes to the instance that hold the 
values that the property would return?

class A(object):
     def __init__(self, dbvaluedict):
         self.__dict__.update(dbvaluedict)


 >>> dbvaluedict = dict('test': 'test')
 >>> a = A(dbvaluedict)
 >>> print a.test
test

If this doesn't help. You might want to start at the beginning and explain what 
it is you are trying to accomplish.  What you are trying to do is very unusual.

-Larry



More information about the Python-list mailing list