简体   繁体   中英

How does function call another function in Python

I want call function dynamically in Python, and code like as:

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. Because "show1" and "show2" has different number of args, and "args" is a list.

Same as always.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM