Python中用字符串调用函数或方法示例代码
作者:Abnerzhao 时间:2023-03-05 15:37:59
前言
本文主要给大家介绍了关于Python用字符串调用函数或方法的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍:
先看一个例子:
>>> def foo():
print "foo"
>>> def bar():
print "bar"
>>> func_list = ["foo","bar"]
>>> for func in func_list:
func()
TypeError: 'str' object is not callable
我们希望遍历执行列表中的函数,但是从列表中获得的函数名是字符串,所以会提示类型错误,字符串对象是不可以调用的。如果我们想要字符串变成可调用的对象呢?或是想通过变量调用模块的属性和类的属性呢?
以下有三种方法可以实现。
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
>>> 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_instance, 'do_' + opname)
>>> 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://segmentfault.com/a/1190000010476065
标签:python,字符串,调用函数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现Flappy Bird源码
2021-12-01 21:49:19
![](https://img.aspxhome.com/file/2023/2/124202_0s.jpg)
使用tensorflow框架在Colab上跑通猫狗识别代码
2022-04-27 04:43:39
![](https://img.aspxhome.com/file/2023/1/104821_0s.png)
SQL Server利用sp_spaceused如何查看表记录存在不准确的情况
2024-01-20 07:40:10
![](https://img.aspxhome.com/file/2023/0/129310_0s.png)
使用Python神器对付12306变态验证码
2021-01-19 00:14:02
![](https://img.aspxhome.com/file/2023/5/118345_0s.gif)
一个输入框提示列表效果
2008-03-09 18:53:00
python matplotlib自定义colorbar颜色条及内置色条详解
2023-04-03 16:50:34
![](https://img.aspxhome.com/file/2023/6/79436_0s.png)
python中将正则过滤的内容输出写入到文件中的实例
2023-12-15 06:56:09
SQL Server异常代码处理的深入讲解
2024-01-22 11:42:58
![](https://img.aspxhome.com/file/2023/8/119258_0s.png)
详解Docker创建Mysql容器并通过命令行连接到容器
2024-01-24 22:25:18
Navicat连接MySQL错误描述分析
2024-01-17 13:39:31
![](https://img.aspxhome.com/file/2023/2/80142_0s.jpg)
Python matplotlib可视化绘图详解
2021-11-11 12:03:26
![](https://img.aspxhome.com/file/2023/0/78480_0s.png)
数组任意位置插入元素,删除特定元素的实例
2024-05-05 09:18:22
Python 选择排序中的树形选择排序
2023-06-10 04:33:32
![](https://img.aspxhome.com/file/2023/3/75893_0s.jpg)
go slice 数组和切片使用区别示例解析
2023-06-22 04:07:16
![](https://img.aspxhome.com/file/2023/0/87610_0s.jpg)
编辑BLOG文章的一些好习惯
2007-11-15 06:35:00
Python 字符串操作方法大全
2023-12-06 04:21:48
Go语言使用钉钉机器人推送消息的实现示例
2024-05-09 14:57:37
![](https://img.aspxhome.com/file/2023/4/127064_0s.png)
BootStrap3学习笔记(一)之网格系统
2024-04-29 13:43:48
![](https://img.aspxhome.com/file/2023/0/132560_0s.png)
Python编写memcached启动脚本代码实例
2023-02-13 19:59:51
使用Python脚本实现批量网站存活检测遇到问题及解决方法
2022-04-12 00:50:03