Home > Article > Backend Development > How to use a variable as a function name in Python?
PHP has the usage of variable functions (see http://www.php.net/manual/en/functions.variable-functions.php)
That is, there is a string variable
Now I want to use the value of this variable as The code to call a certain function name is as follows:
def bar(): return 'bar' foo = 'bar' foo() #此处想调用 bar()
I wonder if Python has such usage?
Haha, python is so powerful, of course python can also support it
Python has an eval function (it seems that many languages have this function) that can solve this problem.
The code is as follows:
def foo(): print 'hi' t = eval('foo') t()
Question 2: Can python import a module that is the value of a certain variable?
foo = 'bar' import foo #此处想导入 bar
Another function is used here. . .
Code:
m = 'sys' exec "import " + m
That’s it ok