0

I have 2 functions as follows:

def test1(var):
    return var*2

def test2(var):
    return var*4

I want to pass a variable to form part of the code, something like below:

var='test2'
def new_test(var,4):
    return var(4)

And I expect the output to be 16 (i.e. output from test2)

In excel, it is achievable via the function of =indirect(...). Is there any way to achieve that in Python?

6
  • Is there some reason you can't do command=test2? Commented Aug 27, 2017 at 5:20
  • @user2357112 Hello user2357112, it is because my current problem has to do with creating a function that takes an argument which will form part of the script within the function. I just revised my codes above for further clarity. Commented Aug 27, 2017 at 5:23
  • In the above case, I have a new function that takes an argument (var) which will either be test1 or test2. And inside the function of new_test, it is written in a way that the argument (var) will either be test1 or test2. Commented Aug 27, 2017 at 5:25
  • 1
    I'm still not seeing anything here that requires you to use a string instead of the actual function object. Commented Aug 27, 2017 at 5:25
  • 1
    Yeah, pretty much. Commented Aug 27, 2017 at 5:29

1 Answer 1

1

Yes, instead of this:

var = 'test2'

def new_test(var, 4):
    return var(4)

You can do this directly:

var = test2

def new_test(var, 4):
    return var(4)

Functions are first class objects in Python.

Sign up to request clarification or add additional context in comments.

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.