python中通过字符串名来调用函数
强调:eval()函数功能虽然强大,但是也很危险,这个方法需要慎重使用。
利用python中的内置函数 eval() ,函数说明:

def eval(*args, **kwargs): # real signature unknown
"""
Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
pass

样例1:

def function2(name, age):
print("name: %s, age: %s" % (name, age)) if __name__ == '__main__':
eval("function2")("Alice", 11) # 或者:
args = ["Alice", 11]
kwargs = {}
eval("function2")(*args, **kwargs) """
输出结果都是:
name: Alice, age: 11
"""

样例2:

class Test(object):
states = [u"大于等于零", u"大于等于二"]
state2function = {u"大于等于零": "check_gt0", u"大于等于二": "check_gt2"} @staticmethod
def check_gt0(x):
return x >= 0 @staticmethod
def check_gt2(x):
return x >= 2 def predict(self, x):
for state in Test.states:
check_ans = eval("Test." + Test.state2function[state])(x) # 调用Test类中的方法
print(state, Test.state2function[state], x, check_ans) if __name__ == '__main__':
test = Test()
test.predict(x=-1)
test.predict(x=1)
test.predict(x=2) """
输出:
大于等于零 check_gt0 -1 False
大于等于二 check_gt2 -1 False
大于等于零 check_gt0 1 True
大于等于二 check_gt2 1 False
大于等于零 check_gt0 2 True
大于等于二 check_gt2 2 True
"""

由字符串函数名得到对应的函数
把函数作为参数的用法比较直观:

def func(a, b):
return a + b def test(f, a, b):
print f(a, b) test(func, 3, 5)

但有些情况下,‘要传递哪个函数’这个问题事先还不确定,例如函数名与某变量有关。可以利用 func = globals().get(func_name)来得到函数:

def func_year(s):
print 'func_year:', s def func_month(s):
print 'func_month:', s strs = ['year', 'month']
for s in strs:
globals().get('func_%s' % s)(s)
"""
输出:
func_year: year
func_month: month
"""

将字符串变成变量名:
https://www.cnblogs.com/kaerxifa/p/11424796.html
参考文章:https://www.cnblogs.com/bymo/p/7327732.html
python中通过字符串名来调用函数的更多相关文章
- Python中的字符串处理
Python转义字符 在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符.如下表: 转义字符 描述 \(在行尾时) 续行符 \\ 反斜杠符号 \' 单引号 \" 双引号 \a ...
- python中根据字符串导入模块module
python中根据字符串导入模块module 需要导入importlib,使用其中的import_module方法 import importlib modname = 'datetime' date ...
- Python中的字符串方法
Python中的字符串方法 字符串类即str提供了许多有用的方法来操纵字符串.具体来说,我们将讨论如下的方法. 搜索字符串内的子字符串. 测试字符串. 格式字符串. 转换字符串. 回顾前面的章节,方法 ...
- python中修改字符串的几种方法
在Python中,字符串是不可变类型,即无法直接修改字符串的某一位字符.因此改变一个字符串的元素需要新建一个新的字符串.常见的修改方法有以下4种. 方法1:将字符串转换成列表后修改值,然后用join组 ...
- python 中的字符串格式化
python 中的字符串格式化 %方式的调用 1.格式化代码 代码 意义 s 字符串,使用str r 字符串,使用repr不使用str c 字符 d 十进制的数字 i 整数 u 无符号整数 o 八进制 ...
- 一句python,一句R︱python中的字符串操作、中文乱码、NaN情况
一句python,一句R︱python中的字符串操作.中文乱码.NaN情况 先学了R,最近刚刚上手Python,所以想着将python和R结合起来互相对比来更好理解python.最好就是一句pytho ...
- Python中Unicode字符串
Python中Unicode字符串 字符串还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特(bit)作为一个字节(byte ...
- 【python】dir(__builtins__)查看python中所用BIF(内置函数)
dir(__builtins__)查看python中所用BIF(内置函数)
- python中的字符串
一.在python中,字符串是不可变类型 通过以下代码说明: >>> s = 'hello, world' >>> id(s) 2108634288304 > ...
随机推荐
- Alpha冲刺(3/10)——2019.4.26
所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(3/10)--2019.4.26 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...
- C/JS_二分法查找
1. 二分法查找 前提: 数据是排好序的. 题设:给出一个有序arr,从中找出key,arr的区间是array[ low , higt]. 步骤: (1)mid=(low+high)/2 (2)arr ...
- 【容斥+组合数】Massage @2018acm徐州邀请赛 E
问题 E: Massage 时间限制: 1 Sec 内存限制: 64 MB 题目描述 JSZKC feels so bored in the classroom that he w ...
- JAVA自学笔记09
JAVA自学笔记09 1.子类的方法会把父类的同名方法覆盖(重写) 2.final: 1)可修饰类.方法.变量 2)修饰类时:此时该类变为最终类,它将无法成为父类而被继承 3)修饰方法时:该方法将无法 ...
- 微信小程序 --- Cannot read property 'setData' of null 解决
在外部定义一个为 this 的 that
- Github超棒资源汇总
Awesome List 中文资源大全 经典编程书籍大全 免费的编程中文书籍索引 awesome-awesomeness-zh_CN https://github.com/jnv/lists awes ...
- OpenCV3 for python3 学习笔记3-----用OpenCV3处理图像一
本文的内容都与图像处理有关,这时需要修改图像,比如要使用具有艺术性的滤镜.外插(extrapolate)某些部分.分割.粘贴或其他需要的操作. 1.不同色彩空间的的转换 OpenCV有数百种关于在不同 ...
- 基于Cesium的demo赏析
更新于2019.2.23 Cesium的强大不用多说,所以有很多政府.组织基于cesium做了一些应用,其中不乏有很多优秀的示例,我们大都可以从中获得对自己的项目有益的东西.另:有的网站需要FQ. 官 ...
- Android 仿QQ界面的实现
废话不说 上图 适合新手学习 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQ ...
- 通过Nginx反向代理之后客户端验证码session不一致造成无法验证通过的问题解决
location / { proxy_pass http://127.0.0.1:9080/app/; proxy_cookie_path /app/ /; proxy_cookie_path /ap ...