eval() 函数执行作为其参数给出的表达式。表达式被评估并解析为有效的 Python 语句。该表达式始终是字符串,并且对于 eval() 函数是必需的。
eval(expression, globals=None, locals=None) #Where expression can be a string to evalate
接受 3 个参数,其中第一个参数是必需的,另外两个是可选的。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 表达式 | 此参数是一个字符串,它将被解析并作为 Python 表达式执行。 | 必需 |
| globals | 它是一个字典。它用于指定可供执行的表达式。 | 可选 |
| locals | 它指定 eval() 中的局部变量和方法。 | 可选 |
| 输入 | 返回值 |
|---|---|
| 表达式 | 表达式的结果。 |
| globals 和 locals 都被省略 | 表达式在当前作用域中执行。 |
| globals 存在;locals 被省略 | globals 将用于全局变量和局部变量。 |
| globals 和 locals 都存在 | 根据参数返回结果。 |
# Perimeter of Square
def calculatePerimeter(l):
return 4 * l
# Area of Square
def calculateArea(l):
return l * l
exp = input("Type a function: ")
for l in range(1, 5):
if exp == "calculatePerimeter(l)":
print("If length is ", l, ", Perimeter = ", eval(exp))
elif exp == "calculateArea(l)":
print("If length is ", l, ", Area = ", eval(exp))
else:
print("Wrong Function")
break
输出
Type a function: calculateArea(l) If length is 1 , Area = 1 If length is 2 , Area = 4 If length is 3 , Area = 9 If length is 4 , Area = 16
from math import *
print(eval('dir()'))
输出
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'os', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
from math import *
print(eval('dir()', {}))
# The code will raise an exception
print(eval('sqrt(25)', {}))
输出
['__builtins__'] Traceback (most recent call last): File "", line 5, in print(eval('sqrt(25)', {})) File " ", line 1, in NameError: name 'sqrt' is not defined
from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))
输出
['__builtins__', 'pow', 'sqrt']
from math import *
a = 169
print(eval('sqrt(a)', {'__builtins__': None}, {'a': a, 'sqrt': sqrt}))
输出
13.0