英文文档:

eval(expressionglobals=Nonelocals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, localscan 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 expressionnormally has full access to the standard builtins module and restricted environments are propagated. If the localsdictionary 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.
  执行动态标表达式求值
说明:
  
  1. 执行动态语句,返回语句执行的值。
>>> eval('1+2+3+4')
10

  2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。

  3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量。

>>> g = {'num':2}

>>> eval('num + 2') #num未定义
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num + 2')
File "<string>", line 1, in <module>
NameError: name 'num' is not defined >>> eval('num + 2',g) #g中有定义num,可执行
4

  4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

>>> g = {'num1':2}
>>> l = {'num2':4}
>>> eval('num1+num2',g,l)
6

  5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

>>> g = {}
>>> eval('abs(-1)',g)
1 >>> g = {'__builtins__':{}}
>>> eval('abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
eval('abs(-1)',g)
File "<string>", line 1, in <module>
NameError: name 'abs' is not defined

  6. 当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。

>>> num = 1
>>> eval('num+2')
3 >>> globals() #返回字典中含有num的key
{'__doc__': None, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>} >>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num+2',{})
File "<string>", line 1, in <module>
NameError: name 'num' is not defined >>> l = locals()
>>> eval('num+2',{},l) #locals参数含有num的key,能求值
3 >>> locals()
{'__doc__': None, 'l': {...}, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>>

Python内置函数(61)——eval的更多相关文章

  1. python 内置函数input/eval(22)

    python的内置函数其实挺多的,其中input和eval算得上比较特殊,input属于交互式内置函数,eval函数能直接执行字符串表达式并返回表达式的值. 一.input函数 input是Pytho ...

  2. Python内置函数(61)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string ...

  3. Python内置函数(19)——eval

    英文文档: eval(expression, globals=None, locals=None) The arguments are a string and optional globals an ...

  4. Python内置函数之eval()

    eval(expression,globals=None,locals=None) 返回表达式的值.第一个参数必须是字符串.第二个参数可选,如果有必须是字典:第三个参数可选,如果有必须是映射对象(比如 ...

  5. Python | 内置函数(BIF)

    Python内置函数 | V3.9.1 | 共计155个 还没学完, 还没记录完, 不知道自己能不能坚持记录下去 1.ArithmeticError 2.AssertionError 3.Attrib ...

  6. python内置函数

    python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...

  7. python 内置函数和函数装饰器

    python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...

  8. Python 内置函数笔记

    其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...

  9. 【转】python 内置函数总结(大部分)

    [转]python 内置函数总结(大部分) python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为 ...

随机推荐

  1. 云计算之路-阿里云上:docker swarm 集群再次出现故障

    非常非常抱歉!16:30 ~ 17:00 左右我们用于跑 ASP.NET Core 站点的 docker swarm 集群再次出现宕机,由此给您带来了很大很大的麻烦,恳请您的谅解! 受此次故障影响的站 ...

  2. 记录一次网站漏洞修复过程(三):第二轮处理(拦截SQL注入、跨站脚本攻击XSS)

    在程序编写的时候采用参数化的SQL语句可以有效的防止SQL注入,但是当程序一旦成型,再去修改大量的数据库执行语句并不是太现实,对网页表单上输入进行校验是易于实现的方法.在webForm 页面中开启校验 ...

  3. python文件基本操作(读,写,追加)

    一:只读(r) f=('d:\ python的联系文件'')   绝对路径和相对路径(绝对路径:能找到文件开始到结束路径,真实存在的路径,相对路径:在绝对路径一致的情况下新建一个文件) f=open( ...

  4. RESTful接口设计原则和优点

    RESTful架构优点: 前后端分离,减少流量 安全问题集中在接口上,由于接受json格式,防止了注入型等安全问题 前端无关化,后端只负责数据处理,前端表现方式可以是任何前端语言(android,io ...

  5. Unity3D判断触摸方向

    据说 Temple Run(神庙逃亡) 就是用这种方式操作的 废话不多说 直接上代码 using UnityEngine; using System.Collections; public class ...

  6. Jmeter + Ant 测试环境搭建 及解决问题: the <jmeter> type doesn't support nested text data

    1.首先确保测试机器中已经按照jdk1.6以上版本,如果没有,那就上官网下载吧. 2.下载Ant,解压至指定目录,并配置好环境变量:http://ant.apache.org/ 在命令行下执行ant ...

  7. python全栈开发-Day5 元组、字典

    python全栈开发-Day5  元组.字典 一.前言 首先,不管学习什么数据类型,我们都带着以下几个问题展开学习: #1:基本使用 1 .用途 2 .定义方式 3.常用操作+内置的方法 #2:该类型 ...

  8. Cannot resolve taglib with uri http://java.sun.com/jsp/jstl/core

    问题 <Spring 实战>第5章,在 IDEA 中 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" pre ...

  9. angularJS前台传list数组,后台springMVC接收数组

    有时候需要在前台自定义对象,然后把对象封装在list中,在传送到后台,这样的思想也比较合理 1. 前台代码 $scope.saveScore = function () { $scope.userSc ...

  10. Linux chgrp命令

    在lunix系统里,文件或目录的权限的掌控以拥有者及所诉群组来管理.可以使用chgrp指令取变更文件与目录所属群组,这种方式采用群组名称或群组识别码都可以.Chgrp命令就是change group的 ...