注:函数 exec 和 eval 均是python的内置函数,即不用导入第三方库便可调用!
目录
(1)函数exec
(2)函数eval
(3)根据官方给出的注释,可知:
(4)代码示例:
exec(object[, globals[, locals]])
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
eval(expression[, globals[, locals]])
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
上面的解析基本都在下面的代码示例实现:
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
>>>如有疑问,欢迎评论区一起探讨