标签:pytho val 应用 int glob ict local pre eva
1、eval()函数介绍
2、eval()应用
eval(source[, globals[, locals]])
功能:将字符串str当成有效的表达式来求值并返回计算结果
参数:
source:一个Python表达式或函数compile()返回的代码对象
globals:可选。必须是dictionary
locals:可选。任意map对象
不传入传入globals 、locals
data1 = ‘1‘
ret1 = eval(data1)
print(ret1, type(ret1)) # 1 <class ‘int‘>
data2 = ‘[1,2,3,4]‘
ret2 = eval(data2)
print(ret2, type(ret2)) # [1, 2, 3, 4] <class ‘list‘>
data3 = ‘(1,2 ,3,4)‘
ret3 = eval(data3)
print(ret3, type(ret3)) # (1, 2, 3, 4) <class ‘tuple‘>
data4 = ‘{"name":"allen", "age":15}‘
ret4 = eval(data4)
print(ret4, type(ret4)) # {‘name‘: ‘allen‘, ‘age‘: 15} <class ‘dict‘>
data5 = ‘{1,2,3,4}‘
ret5 = eval(data5)
print(ret5, type(ret5)) # {1, 2, 3, 4} <class ‘set‘>
ret6 = eval(‘1+1‘)
print(ret6, type(ret6)) # 2 <class ‘int‘>
传入globals 、locals
x = 2
y = 2
num2 = eval("x+y")
print(num2) # 4
num3 = eval("x+y", globals())
print(num3) # 2
num4 = eval("x+y",globals(),locals())
print(num4) # 4
标签:pytho val 应用 int glob ict local pre eva
原文地址:https://www.cnblogs.com/suxianglun/p/9117792.html