how to add property "dynamically"?

akonsu akonsu at gmail.com
Sun Aug 17 00:46:23 CEST 2008


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



More information about the Python-list mailing list