[英]How do i call a method by a string name using python?
I have the following class; 我有以下课程;
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!
No functions get called out, what am i missing? 没有函数被调用,我缺少什么?
gath 盖特
your self.func_list
should be: 您的
self.func_list
应该是:
self.func_list= [('func1','print_func1'),('func2','print_func2')]
And the way your code is written it will, of course, print 'Func Name'
. 当然,编写代码的方式将显示
'Func Name'
。 I guess you probably meant to pass func[0]
there. 我猜您可能打算将
func[0]
传递到那里。
Working example: 工作示例:
>>> 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
maybe offtopic, but maybe your list is actually a dict : 也许是题外话,但也许您的清单实际上是字典:
self.functs = {'func1':'print_func1', ...}
and then call with : 然后致电:
for fn in self.functs.values() : self.__dict__[fn]('Func Name')
or even if you wanted to call all 'func_' functions in your class (no func_list here) : 甚至即使您想调用类中的所有“ 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.