极客小将

您现在的位置是:首页 » python编程资讯

资讯内容

python中eval的用法是什么

极客小将2021-03-02-
简介python中eval的用法:将字符串str当成有效的表达式来求值并返回计算结果,语法为【eval(source[,globals[,locals]])->value】。本教程操作环境:windows7系统、python3.9版,DELLG3电脑,该方法适用于所有品牌电脑。python中eva

极客小将版权所有。

python中eval的用法:将字符串str当成有效的表达式来求值并返回计算结果,语法为【eval(source[, globals[, locals]]) -> value】。wSi少儿编程网-https://www.pxcodes.com

wSi少儿编程网-https://www.pxcodes.com

本教程操作环境:windows7系统、python3.9版,DELL G3电脑,该方法适用于所有品牌电脑。wSi少儿编程网-https://www.pxcodes.com

python中eval的用法:wSi少儿编程网-https://www.pxcodes.com

python eval() 函数的功能:将字符串str当成有效的表达式来求值并返回计算结果。wSi少儿编程网-https://www.pxcodes.com

语法:wSi少儿编程网-https://www.pxcodes.com

eval(source[, globals[, locals]]) -> value

参数:wSi少儿编程网-https://www.pxcodes.com

source:一个Python表达式或函数compile()返回的代码对象wSi少儿编程网-https://www.pxcodes.com

globals:可选。必须是dictionarywSi少儿编程网-https://www.pxcodes.com

locals:可选。任意map对象wSi少儿编程网-https://www.pxcodes.com

如果提供了globals参数,那么它必须是dictionary类型;如果提供了locals参数,那么它可以是任意的map对象。wSi少儿编程网-https://www.pxcodes.com

python的全局名字空间存储在一个叫globals()的dict对象中;局部名字空间存储在一个叫locals()的dict对象中。我们可以用print (locals())来查看该函数体内的所有变量名和变量值。wSi少儿编程网-https://www.pxcodes.com

x = 1 y = 1 num = eval("x+y") print('num',num) def g(): x = 2 y = 2 num1 = eval("x+y") print('num1',num1) num2 =eval("x+y",globals()) print('num2',num2) num3 = eval("x+y",globals(),locals()) print('num3',num3) g() num 2 num1 4 num2 2 num3 4

解析:num2 因为有globals所以是全局变量,执行后结果为4;num3 既有globals 又有locals,仅在此情况下,优先采用locals的值,故计算结果是2wSi少儿编程网-https://www.pxcodes.com

相关免费学习推荐:python视频教程wSi少儿编程网-https://www.pxcodes.com

以上就是python中eval的用法是什么的详细内容,更多请关注少儿编程网其它相关文章!wSi少儿编程网-https://www.pxcodes.com

网友点评

共有5条评论来说两句吧...

在线客服