源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python中用字符串调用函数或方法示例代码

  • 时间:2022-11-22 23:39 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python中用字符串调用函数或方法示例代码
[b]前言[/b] 本文主要给大家介绍了关于Python用字符串调用函数或方法的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: [b]先看一个例子:[/b]
>>> def foo():
    print "foo"

>>> def bar():
    print "bar"

>>> func_list = ["foo","bar"]
>>> for func in func_list:
    func()
TypeError: 'str' object is not callable
我们希望遍历执行列表中的函数,但是从列表中获得的函数名是字符串,所以会提示类型错误,字符串对象是不可以调用的。如果我们想要字符串变成可调用的对象呢?或是想通过变量调用模块的属性和类的属性呢? [b]以下有三种方法可以实现。[/b] [b]eval()[/b]
>>> for func in func_list:
    eval(func)()
foo
bar
eval() 通常用来执行一个字符串表达式,并返回表达式的值。在这里它将字符串转换成对应的函数。eval() 功能强大但是比较危险(eval is evil),不建议使用。 [b]locals()和globals() [/b]
>>> for func in func_list:
    locals()[func]()
foo
bar

>>> for func in func_list:
    globals()[func]()
foo
bar
locals() 和 globals() 是python的两个内置函数,通过它们可以一字典的方式访问局部和全局变量。 [b]getattr()[/b] 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()
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。 参考 [url=https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-from-a-string-with-the-functions-name-in-python]Calling a function of a module from a string with the function's name in Python[/url] [url=https://docs.python.org/3/faq/programming.html#how-do-i-use-strings-to-call-functions-methods]How do I use strings to call functions/methods?[/url]
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部