# eval 计算字符串表达式并返回,做些简单的操作
# 若globals存在则使用globals
# 若locals存在则优先使用locals
a = 10
def eval_test():
b = 20
c = eval('a+b')
print("c:", c)
c = eval('a+b', {"a":1, "b":2})
print("c:", c)
# locals优先使用
c = eval('a+b', {"a":1, "b":2}, {"a":3, "b":4})
print("c:", c)
print("a:", a, "b:", b)
eval_test()
# c: 30
# c: 3
# c: 7
# a: 10 b: 20
class Test:
def __init__(self, name):
self.name= name
# 使用字符串构造类的对象
t = eval("Test('hello')")
print(t.name) # hello
# exec不会返回,会运行并保留上下文
a = 10
# 单条执行对象
b = exec("a=a+2")
print("a:", a) # 12
print("b:", b) # None
# 多条执行对象,以\n进行换行
exec("b=[]\nb.append(2)\nprint(b)") # [2]
print(b) # [2]
exec("t=Test('world')\nprint(t.name)") # world
print(t.name) # world
08-22
1210
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-06
996
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-11