python - How to dynamically call methods within a class using method-name assignment to a variable -
this question has answer here:
class myclass: def __init__(self, i): self.i = def get(self): func_name = 'function' + self.i self.func_name() # <-- not work. def function1(self): //do def function2(self): //do error get: typeerror: 'str' object not callable
could please this. have tried lot of permutations , combinations no avail! (note: 'self.func_name' not work)
def get(self): def func_not_found(): # in case dont have function print "no function "+self.i+" found!" func_name = 'function' + self.i func = getattr(self,func_name,func_not_found) func() # <-- should work!
Comments
Post a Comment