注:函数 exec 和 eval 均是python的内置函数,即不用导入第三方库便可调用!
目录
(1)函数exec
(2)函数eval
(3)根据官方给出的注释,可知:
(4)代码示例:
(1)函数exec
exec(object[, globals[, locals]])
- object:必选参数,表示需要被指定的 Python 代码。它必须是字符串或 code 对象。如果 object 是一个字符串,该字符串会先被解析为一组 Python 语句,然后再执行(除非发生语法错误)。如果 object 是一个 code 对象,那么它只是被简单的执行;
- globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象;
- locals:可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象。如果该参数被忽略,那么它将会取与 globals 相同的值。
def exec(*args, **kwargs): # real signature unknown
"""
Execute the given source in the context of globals and locals.
在全局变量和局部变量的上下文中执行给定的源。
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
源可以是表示一条或多条Python语句的字符串,也可以是compile()返回的代码对 象。 globals必须是一个字典,locals可以是任何映射,默认为当前的globals 和 locals。 如果只给出全局变量,则局部变量默认为全局变量。
"""
pass
(2)函数eval
eval(expression[, globals[, locals]])
- expression 是表达式字符串;
- globals变量作用域,locals变量作用域。解析同 exec 一样;
- 如果忽略后面两个参数,则eval在当前作用域执行。
def eval(*args, **kwargs): # real signature unknown
"""
Evaluate the given source in the context of globals and locals.
在全局变量和局部变量的上下文中计算给定的源。
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
源可以是表示Python表达式的字符串,也可以是compile()返回的代码对象。
globals必须是一个字典,locals可以是任何映射,默认为当前的globals和locals。
如果只给出全局变量,则局部变量默认为全局变量。
"""
pass
(3)根据官方给出的注释,可知:
- exec 和 eval 都是用来 “处理字符串” 的函数;
- exec 把字符串转化成 “待执行的语句”,返回值永远为 None;
- eval 把字符串转换成 “python表达式”,返回表达式计算结果。
(4)代码示例:
上面的解析基本都在下面的代码示例实现:
x = 2
y = 3
print(x * y)
print(eval('x * y', {'x': 6, 'y': 6}))
print(eval('x * y')) # 如果忽略后面两个参数,则eval在当前作用域(x,y=2,3)执行。
output1:
>>>6
>>>36
>>>6
class Eval_demo:
# 定义局部变量result,两个函数demo1和demo2可以互相调用
def demo1(self):
global result
g = {} # 全局变量字典
l = {"x": 2, "y": 4} # 局部变量字典
result = eval("x * y", g, l)
print("demo1: ", result)
def demo2(self):
global result
print("demo2: ", result)
if __name__ == '__main__':
e = Eval_demo()
e.demo1()
e.demo2()
output2:
>>>demo1: 8
>>>demo2: 8
g = {'Flying': 3, "Bulldog": 6}
# 如果 locals 参数被忽略,那么它将会取与 globals 相同的值。
exec("print(Flying * 2 + Bulldog * 3)", g)
output3:
>>>24
# 定义初始int变量
a = 0
b = 0
c = 0
exec('a = 1; b = 2; c = 3') # 多条语句
print("exec:", exec('a * b * c'))
print("eval:", eval('a * b * c'))
print(a, b, c)
output4:
>>>exec: None # 返回值永远为 None
>>>eval: 6 # 返回表达式计算结果
>>>1 2 3
>>>如有疑问,欢迎评论区一起探讨



