You can dynamically add property
s, but properties are added to the class object, not the instance.
Here's an example:
def make_prop(cls, p):
def f(self):
print 'IN %s' % p
return '[%s]' % p
return f
class myClass(object):
pass
# add the properties
for p in ('edgar','allan','poe'):
setattr(myClass, p, property(make_prop(myClass, p)))
y = myClass()
print y.a
print y.b
Prints:
IN allan
[allan]
IN poe
[poe]
Also, it is essential to use make_prop
to create the function object, instead of creating them directly inside the for
loop, due to python's lexical scoping. I.e. this won't work as expected:
# add the properties
for p in ('edgar','allan','poe'):
def f(self):
print 'IN %s' % p
return '[%s]' % p
setattr(myClass, p, property(f))