python的eval()能做什么

官方网址:

https://docs.python.org/3/library/functions.html?highlight=eva#eval

官方描述:

eval(expression[, globals[, locals]])

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 does not contain a value for the key builtins, a reference to the dictionary of the built-in module builtins is inserted under that key 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 with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

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.

Raises an auditing event exec with the code object as the argument. Code compilation events may also be raised.

能做什么?

如上描述:
(1)作用于字符串,让其解析成表达式:

x = 1
print(eval('x+1'))

在这里插入图片描述
(2)如果能解析字符串,是否一些字符串类型的字典、列表等,能否解析:

@字典:

a = "{'a': 'a', 'b': 'b'}"
print(type(eval(a)))

在这里插入图片描述
@列表

a = "[1,2,3,4]"
b = eval(a)
print(type(b))

在这里插入图片描述
(3)gloabals和locals的理解:

x = 10  # 全局变量 gloabals
def fun():

	y = 20  # 局部变量 locals

	# (1)在eval作用域中,没有关于x,y的gloabals或locals,因此调用环境下的gloabals和locals
	a = eval('x+y')
	print('a:', a)  # a的值为30

	# (2)在eval作用域中,只存在关于x,y的gloabals,因此调用作用域下的gloabals
	b = eval('x+y',{'x':1, 'y': 2})
	print('b:', b)  # b的值为3

	# (3)在eval作用域中,存在关于x的gloabals,y的locals,因此调用作用域下x的gloabals和y的locals
	c = eval('x+y',{'x':1, 'y': 2},{'y':3, 'z': 4})
	print('c:', c) # c的值为4

	# (4)非计算表达式,返回数据为空
	d = eval('print(x,y)')
	print('d:', d) # d的值为None

fun()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43431593/article/details/107391827