[英]How does function call another function in Python
I want call function dynamically in Python, and code like as: 我想在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])
But I do not know how to call "show1" or "show2" in callfunc. 但是我不知道如何在callfunc中调用“ show1”或“ show2”。 Because "show1" and "show2" has different number of args, and "args" is a list.
因为“ show1”和“ show2”具有不同数量的args,因此“ args”是一个列表。
def callfunc(self, f, args):
f(*args)
If you can pass function reference as the parameter, you can instead call the function directly. 如果您可以将函数引用作为参数传递,则可以直接调用该函数。 Here is a more flexible way to do this
这是一种更灵活的方法
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])
In this case, the function to be called can be determined and invoked dynamically. 在这种情况下,可以动态确定并调用要调用的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.