Python3中用字符串调用函数或方法

本文介绍了在Python中如何使用字符串来调用函数或方法的三种方法,包括eval()、locals()和globals()以及getattr()。虽然eval()功能强大但存在安全风险,推荐使用locals()和globals()或getattr()来更安全地实现字符串调用。同时强调了在处理字符串到函数映射时的安全考虑和最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用字符串调用函数或方法

先看一个例子:

>>> def foo():
...     print ("foo")
... 
>>> def bar():
...     print ("bar")
... 
>>> func_list = ["foo","bar"]
>>> for func in func_list:
...     func()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'str' object is not callable

用字符串直接掉用方法,报错TypeError: 'str' object is not callable

以下有三种方法可以实现。(建议使用locals()和globals()

eval()

>>> for func in func_list:
...     eval(func)()
... 
foo
bar

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


locals()和globals()

>>> for func in func_list:
...     locals()[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):
...             print("do_foo")
...     def do_bar(self):
...             print("do_bar")
... 
>>> foo_instance = Foo()
>>> f = getattr(foo_instance, 'do_' + 'bar')
>>> f()
do_bar

 

 

参考链接:

https://www.jb51.net/article/120311.htm

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值