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

先看一个例子:

  1. >>> def foo():
  2. print "foo"
  3. >>> def bar():
  4. print "bar"
  5. >>> func_list = ["foo","bar"]
  6. >>> for func in func_list:
  7. func()
  8. TypeError: 'str' object is not callable

我们希望遍历执行列表中的函数,但是从列表中获得的函数名是字符串,所以会提示类型错误,字符串对象是不可以调用的。如果我们想要字符串变成可调用的对象呢?或是想通过变量调用模块的属性和类的属性呢?以下有三种方法可以实现。

eval()

  1. >>> for func in func_list:
  2. eval(func)()
  3. foo
  4. bar

eval() 通常用来执行一个字符串表达式,并返回表达式的值。在这里它将字符串转换成对应的函数。eval() 功能强大但是比较危险(eval is evil),不建议使用。

locals()和globals()

  1. >>> for func in func_list:
  2. locals()[func]()
  3. foo
  4. bar
  5. >>> for func in func_list:
  6. globals()[func]()
  7. foo
  8. bar

locals() 和 globals() 是python的两个内置函数,通过它们可以一字典的方式访问局部和全局变量。

getattr()

getattr() 是 python 的内建函数,getattr(object,name) 就相当于 object.name,但是这里 name 可以为变量。

返回 foo 模块的 bar 方法

  1. >>> import foo
  2. >>> getattr(foo, 'bar')()

返回 Foo 类的属性

  1. >>> class Foo:
  2. def do_foo(self):
  3. ...
  4. def do_bar(self):
  5. ...
  6. >>> f = getattr(foo_instance, 'do_' + opname)
  7. >>> f()

标准库operator下的methodcaller函数

 

  1. >>> class Foo:
  2. def do_foo(self):
  3. print 1
  4. def do_bar(self):
  5. print 2
  6. >>> f = Foo()
  7. >>> from operator import methodcaller
  8. >>> methodcaller('do_foo')(f)

 

参考

Calling a function of a module from a string with the function's name in Python

How do I use strings to call functions/methods?

https://blog.csdn.net/u013679490/article/details/54767170

posted @ 2020-07-29 10:37  沐夏aaron  阅读(484)  评论(0)    收藏  举报