用字符串调用函数或方法
先看一个例子:
>>> def foo():
... print ("foo")
...
>>> def bar():
... print ("bar")
...
>>> func_list = ["foo","bar"]
>>> for func in func_list:
... func()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: 'str' object is not callable
用字符串直接掉用方法,报错TypeError: 'str' object is not callable
以下有三种方法可以实现。(建议使用locals()和globals())
eval()
>>> for func in func_list:
... eval(func)()
...
foo
bar
eval() 通常用来执行一个字符串表达式,并返回表达式的值。在这里它将字符串转换成对应的函数。eval() 功能强大但是比较危险(eval is evil),不建议使用。
locals()和globals()
>>> for func in func_list:
... locals()[func]()
...
foo
bar
locals() 和 globals() 是python的两个内置函数,通过它们可以一字典的方式访问局部和全局变量。
getattr()
getattr() 是 python 的内建函数,getattr(object,name) 就相当于 object.name,但是这里 name 可以为变量。
返回 foo 模块的 bar 方法
>>> import foo
>>> getattr(foo, 'bar')()
返回 Foo 类的属性
>>> class Foo:
... def do_foo(self):
... print("do_foo")
... def do_bar(self):
... print("do_bar")
...
>>> foo_instance = Foo()
>>> f = getattr(foo_instance, 'do_' + 'bar')
>>> f()
do_bar
参考链接: