0

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.

2 Answers 2

5

Same as always.

def callfunc(self, f, args):
  f(*args)
Sign up to request clarification or add additional context in comments.

6 Comments

And the language spec for that is here.
Now this answer in python2.7 (inferring from using print as a statement) raises: TypeError: show1() takes exactly 2 arguments (3 given).
@Hyperboreus: Hardly my fault.
Yes, but in which respect does your post answer OP's question, taking his code snippet into consideration?
@Hyperboreus: His typo is still not my fault.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.