简体   繁体   中英

How to call make a variable a callable function in Python

I have a code in which the user chooses the function he wants to execute. There is no definite amount of functions as the functions may increase in the future. I am storing the value fetched from the User input into a variable. I want to make the variable callable.

functions = ['add','sub','mul']
a = 10
b = 5

x = input('Choose a function : ')

def add():
    print(a+b)
def mul():
    print(a*b)
def sub():
    print(a-b)

x()

I want the variable 'x' to be called and executed as a function.

I think, correct solution for this will be dict . Also it gives you some flexibility to give different string keywords for functions. Code:

def add(a, b):
    print(a + b)


def mul(a, b):
    print(a * b)


def sub(a, b):
    print(a - b)


functions = {
    'add': add,
    'sub': sub,
    'mul': mul
}

a = 10
b = 5

x = input('Choose a function : ')

if x not in functions:
    print(f"Function \"{x}\" is not defined.")
else:
    functions[x](a, b)

But if you think that it's 100% neccesary to call function by string name, you can get reference to function from globals() :

func = globals().get(x, None)
if not x:
    print(f"Function \"{x}\" is not defined.")
else:
    func(a, b)

I notice you don't use functions , but you're on to something there. It should be a dictionary of names to functions

def add():
    ...

functions = {'add': add,'sub': sub, 'mul': mul}

choice = input('Choose a function : ')
f = functions[choice]

f()

eval() could work for you, just know that it allows arbitrary code execution, so be careful how you allow values to get passed to it.

Eg:

$ python
Python 3.7.2 (default, Feb 12 2019, 08:15:36) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def a():
...     print('a')
... 
>>> def b():
...     print('b')
... 
>>> func = eval('a')
>>> func()
a
>>> func = eval('b')
>>> func()
b
>>> 

Or with the user selection step:

# ...
>>> func_choice = input('Choose a function: ')
Choose a function: a
>>> func = eval(func_choice)
>>> func()
a
>>> 

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