我有以下课程;
class myStringMethod():
def __init__(self):
self.func_list= [('func1','print_func1()'),('func2','print_func2()')]
def print_func1(self, name):
print name
def print_func2(self, name):
print name
def call_func_by_name(self):
for func in self.func_list:
getattr(self, func[1])('Func Name')
if __name__=='__main__':
strM = myStringMethod()
strM.call_func_by_name() #Nothing prints out!
没有函数被调出,我缺少什么?
加特
答案 0 :(得分:3)
您的self.func_list
应该是:
self.func_list= [('func1','print_func1'),('func2','print_func2')]
编写代码的方式当然会打印'Func Name'
。我猜你可能打算通过func[0]
。
工作示例:
>>> class myStringMethod():
def __init__(self):
self.func_list= [('func1','print_func1'),('func2','print_func2')]
def print_func1(self, name):
print(name)
def print_func2(self, name):
print(name)
def call_func_by_name(self):
for func in self.func_list:
getattr(self, func[1])('Func Name')
>>> myStringMethod().call_func_by_name()
Func Name
Func Name
答案 1 :(得分:0)
也许是offtopic,但也许你的名单实际上是一个字典:
self.functs = {'func1':'print_func1', ...}
然后拨打:
for fn in self.functs.values() : self.__dict__[fn]('Func Name')
或者即使你想调用你班级中的所有'func_'函数(这里没有func_list):
@classmethod
def call_func_by_name(cls)
for n,f in cls.__dict__.values() :
if n.startswith('print_') and hasattr(f,'__call__'): f('Hello')