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?

user7786493
  • 443
  • 3
  • 6
  • 14
  • Is there some reason you can't do `command=test2`? – user2357112 Aug 27 '17 at 05: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. – user7786493 Aug 27 '17 at 05: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. – user7786493 Aug 27 '17 at 05:25
  • 1
    I'm still not seeing anything here that requires you to use a string instead of the actual function object. – user2357112 Aug 27 '17 at 05:25
  • user2357112, do you mean that in this case I can simply type test1 (as an object without single quotation) as an argument passing into the new_test as follows: print(new_test(test2,4)) – user7786493 Aug 27 '17 at 05:28
  • 1
    Yeah, pretty much. – user2357112 Aug 27 '17 at 05:29

1 Answers1

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.

wim
  • 338,267
  • 99
  • 616
  • 750