[英]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.