class MyClass:
def __init__(self, i):
self.i = i
def get(self):
func_name = 'function' + self.i
self.func_name() # <-- this does NOT work.
def function1(self):
//do something
def function2(self):
//do something
我得到的错误: TypeError:'str'对象不可调用
请有人帮忙解决这个问题。我尝试了很多排列和组合,但无济于事! (注意:'self.func_name'也不起作用)
答案 0 :(得分:33)
def get(self):
def func_not_found(): # just in case we dont have the function
print 'No Function '+self.i+' Found!'
func_name = 'function' + self.i
func = getattr(self,func_name,func_not_found)
func() # <-- this should work!
答案 1 :(得分:4)
两件事:
在第8行使用中,
func_name ='function'+ str(self.i)
将字符串定义为函数映射,
self.func_options = {'function1': self.function1,
'function2': self.function2
}
所以看起来应该是:
类MyClass:
def __init__(self, i):
self.i = i
self.func_options = {'function1': self.function1,
'function2': self.function2
}
def get(self):
func_name = 'function' + str(self.i)
func = self.func_options[func_name]
func() # <-- this does NOT work.
def function1(self):
//do something
def function2(self):
//do something