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 ...
随机推荐
- 编写和执行C#代码的插件:CS-Script for Notepad++
这个插件可以方便得让您在Notepad++编辑器中编辑和执行C#代码(脚本).它具备通用的C#智能感知和项目任务管理功能,方式非常类似于MS Visual Studio.除了这一点,它提供了通用的调试 ...
- Android之TelephonyManager
在Android平台中,通过TelephonyManager可以访问与手机通讯相关的信息,比如设备信息.网络信息及SIM卡信息,同时还可以监听电话的相关状态.下面我们通过几个方面来说明Android平 ...
- Android电话拨打权限绕过漏洞(CVE-2013-6272)分析
原文:http://blogs.360.cn/360mobile/2014/07/08/cve-2013-6272/ 1. CVE-2013-6272漏洞背景 CVE-2013-6272是一个安卓平台 ...
- Bootstrap全局CSS样式之表格
.table--基础表格样式. .table-striped--给<tbody>之内的每一行添加斑马条纹样式: .table-bordered--为表格添加边框: .table-hover ...
- MySQL的IFNULL函数
MySQL函数里有一个很有用的函数IFNULL,它的形式是IFNULL(fieldA,fieldB),意义是当字段fieldA是NULL时取fieldB,不是NULL时取fieldA的值. 这个函数与 ...
- 将Tp-link无线路由器桥接到Dlink无线路由器上
笔者家中原有两台笔记本和两台IPad,通过一台Dlink无线路由器(型号DIR-612,以下简称Dlink)上网,Dlink以PPPOE方式连到小区宽带.一直还可以. 后来为了练习Linux,启用了一 ...
- 在服务器端判断request来自Ajax请求(异步)还是传统请求(同步)
两种请求在请求的Header不同,Ajax 异步请求比传统的同步请求多了一个头参数 1. 传统同步请求参数 accept text/html,application/xhtml+xml,applica ...
- 如何为Android上的产品设计一款合适的图标
如 果你已经完成了你的app,你一定会马上向其它人宣布这件事情.但是你需要注意一个很重要的问题,那就是app的图标.你的图标可能在项目启动之 前就已经设计好了,但我不喜欢这样,如果app没有完成实际上 ...
- fatal: incorrect checksum in control file
在网上搜到 7. 修改pg_controlfile的checksum源码, 不check. vi src/backend/access/transam/xlog.c 注释checksum部分 ...
- 把mysql数据库生成数据字典,直接可用
便于查看数据库表.字段,做一个数据字典是很有必要的,下面只需要简单更改下配置就可以用了,样式也是挺好的. <?php header('content-type:text/html;charset ...