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

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

高洛峰
Release: 2016-10-18 10:26:35
Original
1736 people have browsed it

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()
Copy after login

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()
Copy after login

Question 2: Can python import a module that is the value of a certain variable?

foo = 'bar'
import foo #此处想导入 bar
Copy after login

Another function is used here. . .

Code:

m = 'sys'
exec "import " + m
Copy after login

That’s it ok

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template