Home  >  Article  >  Backend Development  >  How to use a variable as a function name in Python?

How to use a variable as a function name in Python?

高洛峰
高洛峰Original
2016-10-18 10:26:351704browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn