I have a generic class that I add dynamic properties to, and I want to add methods dynamically to instances, as certain instances will have different methods, but they need to access these dynamic properties.
How do I do this?
class GenericComponent:
def __init__(self, ID):
self.ID = ID
@classmethod
def addMethod(cls, func):
return setattr(cls, func.__name__, types.MethodType(func, cls))
In my logic, as I build up these generic components I have something like this, so that for different instances I will have the same method name, but the logic inside it is different.
if t==0:
def toString(target):
print "toString: ", target
attrs = vars(target)
print ', '.join("%s: %s" % item for item in attrs.items())
obj = GenericComponent(ID)
obj.ID = ID
obj.name = "some random name"
obj.addMethod(toString)
obj.toString()
Unfortunately when I call obj.toString()
it won't see obj.name