Docs/Python/通过函数名的字符串调用函数.md
2022-10-18 16:59:37 +08:00

69 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

有时需要调用的函数,事先并不确定,需要代码运行时,根据实际情况传入,但是字符串对象并不能作为函数名称调用,会有类型错误。
python提供了几种方法可以实现这种需求
```
def foo():
print("foo")
def bar():
print("bar")
func_list=["foo","bar"]
```
### eval()
```
for func in func_list:
eval(func)()
```
结果如下
```
foo
bar
```
***eval()通常用来执行一个字符串表达式并返回表达式的值这里。它将字符串转换成对应的函数。eval()函数功能强大,但是比较危险,不建议使用。***
### locals()和globals()
```
for func in func_list:
locals()[func]()
```
```
for func in func_list:
globals()[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):
...
def do_bar(self):
...
f = getattr(Foo, 'do'+opname) # eq f_instance = Foo();f=getattr(f_instance, 'do'+opname)
f()
```
### operator.methodcaller
operator.methodcaller() 创建一个可调用对象,并同时提供所有必要参数, 然后调用的时候只需要将实例对象传递给它即可.
```
f = methodcaller('name')
f(b)
结果为b.name()的执行结果
f = methodcaller('name', 'foo', bar=1)
f(b)
将返回 b.name('foo', bar=1)的结果
```