python 使用函数名的字符串调用函数(4种方法)

先看一个例子:

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)

  

 

posted @ 2020-04-26 21:59  JIMfan  阅读(8872)  评论(0编辑  收藏  举报