先看一個例子:
def foo():
print("foo")
def bar():
print("bar")
func_list = ["foo", "bar"]
for func in func_list:
func()
我們希望遍歷執行列表中的函數,但是從列表中獲得的函數名是字符串,所以會提示類型錯誤,字符串對象是不可以調用的。如果我們想要字符串變成可調用的對象呢?或是想通過變量調用模塊的屬性和類的屬性呢?以下有三種方法可以實現。
eval()
for func in func_list:
eval(func)()
foo
bar
eval() 可以把字符串里的字符轉換為可執行代碼,但只支持一行字符。可以返回執行后得到的值。在這里它將字符串轉換成對應的函數。
locals()和globals()
for func in func_list:
print(locals())
>>>'__name__': '__main__', '__doc__': None, '__package__': None, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None,
'foo': <function foo at 0x0000000002061E18>, 'bar': <function bar at 0x00000000028C98C8>, 'func_list': ['foo', 'bar'], 'func': 'foo'}
>>>
>>>
locals() 和 globals() 是python的兩個內置函數,以字典類型返回當前位置的全部局部和全部全局變量.
for func in func_list:
locals()[func]()
foo
bar
for func in func_list:
globals()[func]()
foo
bar
>>>foo
>>>bar
>>>foo
>>>bar
getattr()
getattr() 是 python 的內建函數,getattr(object,name) 就相當於 object.name,但是這里 name 可以為變量。返回 foo 模塊的 bar 方法
import foo getattr(foo, 'bar')()
返回 Foo 類的屬性
class Foo:
def do_foo(self):
...
def do_bar(self):
...
f = getattr(foo_instance, 'do_' + opname)
f()
標准庫operator下的methodcaller函數
class Foo:
def do_foo(self):
print
1
def do_bar(self):
print
2
f = Foo()
from operator import methodcaller
methodcaller('do_foo')(f)
