[英]How does function call another function in Python
我想在Python中动态调用函数,并且代码如下:
class A:
def show1(self, x) :
print x
def show2(self, x, y) :
print x, y
def callfunc(self, f, args) :
#TODO: call function f with args
pass
c = A()
c.callfunc(c.show1, [1])
c.callfunc(c.show2, [1,2])
但是我不知道如何在callfunc中调用“ show1”或“ show2”。 因为“ show1”和“ show2”具有不同数量的args,因此“ args”是一个列表。
def callfunc(self, f, args):
f(*args)
如果您可以将函数引用作为参数传递,则可以直接调用该函数。 这是一种更灵活的方法
class A:
def show1(self, x) :
print x
def show2(self, x, y) :
print x, y
def callfunc(self, f, args) :
return getattr(self, f)(*args)
c = A()
c.callfunc("show1", [1])
c.callfunc("show2", [1,2])
在这种情况下,可以动态确定并调用要调用的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.