first commit
This commit is contained in:
commit
ba848e218d
1001 changed files with 152333 additions and 0 deletions
69
Python/通过函数名的字符串调用函数.md
Normal file
69
Python/通过函数名的字符串调用函数.md
Normal file
|
@ -0,0 +1,69 @@
|
|||
有时需要调用的函数,事先并不确定,需要代码运行时,根据实际情况传入,但是字符串对象并不能作为函数名称调用,会有类型错误。
|
||||
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)的结果
|
||||
```
|
Loading…
Add table
Add a link
Reference in a new issue