Sunday, March 20, 2011

Use a list of strings to dynamically add properties to a class

Got #1 now.  The idea is that we need to add the properties as attributes of the class.  (Although it seems like one could also add the properties as attributes of an object.)  The function looks something like this:




class Test(object):

stat_list = ["x", "y", "z"]

def __init__(self):

for stat in self.stat_list:

name = '_'+stat.lower()

setattr(self.__class__, name, 0)

setattr(self.__class__,

stat.lower(),

property(lambda self: getattr(self, name),

lambda self, value: setattr(self, name, value)))


Update:
Apparently, I need to be creating getter/setters for the object not the class. The odd thing is that I cannot now access the properties through ._stat

stat_list = ["x", "y", "z"]
for stat in self.stat_list:
name = '_'+stat.lower()
#self.__setattr__(name, 0)
self.__setattr__(stat.lower(),
property(lambda self: getattr(self, name),
lambda self, value: setattr(self, name, value)))
print "Added: " + stat.lower() + " " + str(eval("self."+stat.lower()))

No comments: