Python学习笔记011——内置函数eval()
1 描述
eval() 函数用来执行一个字符串表达式,并返回表达式的值
2 语法
原文
eval(expression[, globals=None[, locals=None]])
expression(sourse) -- 字符串表达式。也即,再写该表达式时不能忘记引号“ ”
=语句字符串
globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
= 全局变量,若有,必须是字典。
locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
=局部变量,若有,必须是字典,若无,则等同于globals
3 返回值
返回表达式expression执行结果
4 练习
4.1 执行动态语句
>>> eval("1+2")
3
print(eval("1+2")) #3
4.2 globals 与locals 省略
官方示例
>>> x=1
>>> eval("x+1")
2
也可以时多个参数
x = 1
y = 2
a = eval("x+y")
print("a =",a)
运行:
a = 3
注意:
a = eval("x+y")
等价于
a = eval("x+y",{"x":1,"y":2},{"x":1,"y":2})
4.2 globals和locals省略问题
x = 100
y = 200
ls = {"x":1,"y":2}
c = eval("x+y",ls)
print("c =",c)
print("x = %d,y = %d"%(x,y))
运行
c = 3 x = 100,y = 200
x = 100
y = 200
ls = {"x":1,"y":2}
gs = {"x":3,"y":4}
a = eval("x+y",ls,gs)
print("a =",a)    #a = 7
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))    #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200
print("-------------------------------")
b = eval("x+y",ls)
print("b =",b)    #b = 3
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))    #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200
print("-------------------------------")
c = eval("x+y",ls,None)
print("c =",c)    #c = 3
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))     #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200
print("-------------------------------")
d = eval("x+y",None,gs)
print("d =",d)    d = 7
print("ls[x] = %d,ls[y] = %d"%(ls["x"],ls["y"]))    #ls[x] = 1,ls[y] = 2
print("gs[x] = %d,gs[y] = %d"%(gs["x"],gs["y"]))    #gs[x] = 3,gs[y] = 4
print("x = %d, y = %d"%(x,y))    #x = 100, y = 200
运行
a = 7 ls[x] = 1,ls[y] = 2 gs[x] = 3,gs[y] = 4 x = 100, y = 200 ------------------------------- b = 3 ls[x] = 1,ls[y] = 2 gs[x] = 3,gs[y] = 4 x = 100, y = 200 ------------------------------- c = 3 ls[x] = 1,ls[y] = 2 gs[x] = 3,gs[y] = 4 x = 100, y = 200 ------------------------------- d = 7 ls[x] = 1,ls[y] = 2 gs[x] = 3,gs[y] = 4 x = 100, y = 200
4.4关于变量绑定时的报错
尽管 x 已经定义,但是不是全局变量
>>> {"x":1}
{'x': 1}
>>> eval("x+1")   #   在全部变量中没有定义
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined
>>> a = {"x":1}
>>> eval("a['x']+1")  # 这里一定要注意不能内外均是双引号,这样会报错
2
>>> a = {"x":1}
>>> eval("x+1",a)  #在a中有x的定义,可以执行
2
5 原技术文档
eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1
>>> eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be None.
Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().
See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.
6 参考
https://www.cnblogs.com/sesshoumaru/p/5995712.html
- 
6 参考
 
Python学习笔记011——内置函数eval()的更多相关文章
- Python学习笔记011——内置函数exec()
		
1 描述 把一个字符串当成语句执行 exec() 执行储存在字符串或文件中的 Python 语句,相比于 eval() , exec() 可以执行更复杂的 Python 代码. exec函数和ev ...
 - python学习笔记011——内置函数pow()
		
1 语法 pow(x, y[, z]) x -- 数值表达式. y -- 数值表达式. z -- 数值表达式. 函数是计算 x 的 y 次方,如果 z 在存在,则再对结果进行取模,其结果等效于pow( ...
 - python学习笔记011——内置函数dir()
		
1 描述 dir()函数可以查看(打印)对象的属性和方法.不管时那种对象(python中一切皆对象)类型(数据,模块)都有自己的属性和方法. dir() 函数不带参数时,返回当前范围内的变量.方法和定 ...
 - python学习笔记011——内置函数__module__、__name__
		
1 __module__描述 __module__ : 如果当前模块为顶层模块执行 则打印__main__ 如果当前模块为被调用模块的时候 打印当前模块的名称 2 __module__示例 def f ...
 - python学习笔记011——内置函数sorted()
		
1 描述 sorted() 函数对所有可迭代的对象进行排序操作. sorted() 与sort()函数之间的区别 1 排序对象 sorted:所有可迭代对象的排序 sort:list列表的排序 2 返 ...
 - python学习笔记011——内置函数filter()
		
1 描述 filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表. 2 语法 filter(function, iterable) function -- 函数,过 ...
 - python学习笔记011——内置函数sum()
		
1 描述 sum() 方法对系列进行求和计算. 2 语法 sum(iterable[, start]) iterable:可迭代对象,如列表. start:指定相加的参数,如果没有设置这个值,默认为0 ...
 - python学习笔记011——内置函数__sizeof__()
		
1 描述 __sizeof__() : 打印系统分配空间的大小 2 示例 def fun(): pass print(fun.__sizeof__()) 运行 112
 - Python学习笔记-Day3-python内置函数
		
python内置函数 1.abs 求绝对值 2.all 判断迭代器中的所有数据是否都为true 如果可迭代的数据的所有数据都为true或可迭代的数据为空,返回True.否则返回False 3.a ...
 
随机推荐
- Visual Studio Code 构建C/C++开发环境
			
转自: https://blog.csdn.net/lidong_12664196/article/details/68928136#visual-sutdio-code%E4%BB%A5%E5%8F ...
 - Linux C Socket编程发送结构体、文件详解及实例
			
利用Socket发送文件.结构体.数字等,是在Socket编程中经常需要用到的.由于Socket只能发送字符串,所以可以使用发送字符串的方式发送文件.结构体.数字等等. 本文:http://www.c ...
 - C#读写txt文件的两种方法介绍[转]
			
C#读写txt文件的两种方法介绍 1.添加命名空间 System.IO; System.Text; 2.文件的读取 (1).使用FileStream类进行文件的读取,并将它转换成char数组,然后输出 ...
 - 【反射】Reflect Class Field Method Constructor
			
关于反射 Reflection 面试题,什么是反射(反射的概念)? 主要是指程序可以访问,检测和修改它本身状态或行为的一种能力,并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义 ...
 - 使用 Shell 脚本自动化 Linux 系统维护任务
			
如果一个系统管理员花费大量的时间解决问题以及做重复的工作,你就应该怀疑他这么做是否正确.一个高效的系统管理员应该制定一个计划使得其尽量花费少的时间去做重复的工作.因此尽管看起来他没有做很多的工作,但那 ...
 - FM遇到错误RQP-DEF-0354和QE-DEF-0144
			
版本:Cognos 10.2.1 系统:Win10 操作过程:在FM调用了一个存储过程,其中引用了前端page页面的参数如下图所示,在验证和保存查询主题的时候一直提示参数没有替换值,错误 信息如下图所 ...
 - Mac 苹果OS X小技巧:如何更改文件的默认打开方式
			
OS X小技巧:如何更改文件的默认打开方式 1.command + i 打开简介 2.选择合适的软件打开方式 3.选择全部更改 如图: 转自:http://digi.tech.qq.com/a/201 ...
 - MySQL数据源在Spring中的配置
			
干脆把MySQL的数据源配置也一起放这里,以备不时之需. MySQL的驱动包可以从这里 http://pan.baidu.com/s/1d02aZ 下载. 以下粗体部分是需要你根据实际情况调整的. & ...
 - C#.NET常见问题(FAQ)-如何把函数名作为参数传递给另一个函数
			
在主窗体中使用的还是普通的函数,但是test函数有一个新的参数,就是method 这个method所指向的就是前面委托定义的method 更多教学视频和资料下载,欢迎关注以下信息: 我的优 ...
 - 单点登录(SSO)(原创)
			
单点登录(Single Sign On),简称为 SSO,是目前比较流行的企业业务整合的解决方案之一.SSO的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统. 下面的sso ...