英文文档:

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.
说明:
  
  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内置函数(19)——eval的更多相关文章

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

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

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

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

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

    英文文档: oct(x) Convert an integer number to an octal string. The result is a valid Python expression. ...

  4. Python内置函数(19)-slice

    官方文档 class slice(stop) class slice(start, stop[, step]) Return a slice object representing the set o ...

  5. Python内置函数之eval()

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

  6. python内置函数,匿名函数

    一.匿名函数 匿名函数:为了解决那些功能很简单的需求而设计的一句话函数 def calc(n): return n**n print(calc(10)) #换成匿名函数 calc = lambda n ...

  7. Python之路(第八篇)Python内置函数、zip()、max()、min()

    一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算,如果全部都是true,就返回true, 但是如果是空字符串.空列表也返回t ...

  8. Python之路Python内置函数、zip()、max()、min()

    Python之路Python内置函数.zip().max().min() 一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算, ...

  9. python内置函数简单归纳

    做python小项目的时候发现熟练运用python内置函数,可以节省很多的时间,在这里整理一下,便于以后学习或者工作的时候查看.函数的参数可以在pycharm中ctrl+p查看. 1.abs(x):返 ...

随机推荐

  1. ASP.NET Core 的 `Core` 有几种写法?

    一.概述 本文将会根据情况持续更新. 作为一个 Framework,ASP.NET Core 提供了诸多的扩展点.使用内置的组件和默认的配置通常就能够满足部分需求,当需要扩展的时就需要先去找出这些扩展 ...

  2. UOJ#7. 【NOI2014】购票 点分治 斜率优化 凸包 二分

    原文链接https://www.cnblogs.com/zhouzhendong/p/UOJ7.html 题解 这题是Unknown的弱化版. 如果这个问题出在序列上,那么显然可以CDQ分治 + 斜率 ...

  3. C语言第01次作业--顺序、分支结构

    1.本章学习总结 1.1 思维导图 1.2本章学习体会及代码量学习体会 1.2.1学习体会 本周我学到了很多C语言中基础的结构和语法(见思维导图),能对一些生活中的简单问题对应编写程序解决一些这些简单 ...

  4. jar文件内lib引用的jar插件修改后更新

    打包的java服务在第三方jar进行修改后,要更新线上的jar包时,直接替换原有lib引用的jar文件,会造成服务起不来, 可在本地clean install之后,用线上的classes文件夹替换本地 ...

  5. vue-cli3.0安装element-ui组件及按需引入element-ui组件

    在VUE-CLI 3下的第一个Element-ui项目(菜鸟专用) (https://www.cnblogs.com/xzqyun/p/10780659.html) 上面这个链接是vue-cli3.0 ...

  6. 动态DP之全局平衡二叉树

    目录 前置知识 全局平衡二叉树 大致介绍 建图过程 修改过程 询问过程 时间复杂度的证明 板题 前置知识 在学习如何使用全局平衡二叉树之前,你首先要知道如何使用树链剖分解决动态DP问题.这里仅做一个简 ...

  7. 2018-2019-2 网络对抗技术 20162329 Exp5 MSF基础应用

    目录 Exp5 MSF基础应用 一.基础问题回答 二.攻击系统 ms08_067攻击(成功) 三.攻击浏览器 ms11_050_mshtml_cobjectelement(Win7失败) 手机浏览器攻 ...

  8. sudo命令详解

    语法 sudo(选项)(参数) 选项 选项 说明 -b 在后台执行指令: -h 显示帮助: -H 将HOME环境变量设为新身份的HOME环境变量: -k 结束密码的有效期限,也就是下次再执行sudo时 ...

  9. 怎么修改kodexplorer网盘下的版权

    前言: 要说kodexplorer,可是个好东西,在线web管理服务器文件,着实是网站管理员的好助手.内置的adminer管理数据库,用起来也是很顺手. 这么好的工具,还是免费的.但就是页面底部有ko ...

  10. 封装ajax原理

    封装ajax原理 首先处理 用户如果不传某些参数,设置默认值 type默认get 默认url为当前页 默认async方式请求 data数据默认为{} 处理用户传进来的参数对象 遍历,拼接成key=va ...