eval函数使用教程

eval()函数用于将字符串作为Python表达式进行求值,返回计算结果。它可以访问全局和局部命名空间,动态改变代码。然而,使用时需谨慎,因为它可能引发安全问题。在给定的例子中,eval()被用来计算字符串表示的数学表达式,并展示了如何在不同上下文中使用它。
摘要由CSDN通过智能技术生成

python eval函数功能:将字符串str当成有效的表达式来求值并返回计算结果。

函数定义:

1

eval(expression, globals=None, locals=None)

将字符串str当成有效的表达式来求值并返回计算结果。globals和locals参数是可选的,如果提供了globals参数,那么它必须是dictionary类型;如果提供了locals参数,那么它可以是任意的map对象。

python的全局名字空间存储在一个叫globals()的dict对象中;局部名字空间存储在一个叫locals()的dict对象中。我们可以用print (locals())来查看该函数体内的所有变量名和变量值。

Python版本兼容:

  1. Python2.7
  2. Python3.x

eval()主要作用:

1)在编译语言里要动态地产生代码,基本上是不可能的,但动态语言是可以,意味着软件已经部署到服务器上了,但只要作很少的更改,只好直接修改这部分的代码,就可立即实现变化,不用整个软件重新加载。
2)在machin learning里根据用户使用这个软件频率,以及方式,可动态地修改代码,适应用户的变化。

英文解释:

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:


 

关于eval():

将字符串string对象转化为有效的表达式参与求值运算返回计算结果。

语法上:

调用的是:eval(expression,globals=None, locals=None)返回的是计算结果

其中:

1、expression是一个参与计算的python表达式

2、globals是可选的参数,如果设置属性不为None的话,就必须是dictionary对象了

3、locals也是一个可选的对象,如果设置属性不为None的话,可以是任何map对象了

4、python是用命名空间来记录变量的轨迹的,命名空间是一个dictionary,键是变量名,值是变量值。


#!usr/bin/env python
#encoding:utf-8
import math
def eval_test():
 l='[1,2,3,4,[5,6,7,8,9]]'
 d="{'a':123,'b':456,'c':789}"
 t='([1,3,5],[5,6,7,8,9],[123,456,789])'
 print '--------------------------转化开始--------------------------------'
 print type(l), type(eval(l))
 print type(d), type(eval(d))
 print type(t), type(eval(t))
if __name__=="__main__":
 eval_test()
x = 1
y = 1
num1 = eval("x+y")
print (num1)
def g(): 
 x = 2 
 y = 2 
 num3 = eval("x+y") 
 print (num3)  
 num2 = eval("x+y",globals()) 
 #num2 = eval("x+y",globals(),locals()) 
 print (num2)
  
g()

num1的值是2;num3的值也很好理解,是4;num2的值呢?由于提供了globals()参数,那么首先应当找全局的x和y值,也就是都为1,那么显而易见,num2的值也是2。如果注释掉该句,执行下面一句呢?根据第3点可知,结果为4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值