x = 30
def out():
x = 50
def inner():
print x
print locals()
return inner
out()() # 此处 print locals() 结果 {'x': 50}
x =30
def out():
x = 50
def inner():
print x
print locals()
exec 'print x' in globals(), locals()
return inner
out()() # 此处 print locals() 结果 {}
1
daya0576 2017-10-10 17:35:55 +08:00
exec 'print x' in locals(), globals()
这句话的意思是: 把 locals()返回的字典, 当做'print x'的全局域(global scope) 把 globals()返回的字典, 作为要执行的'print x'的 local scope 所以 exec 'print x' in globals(), locals() 就相当于 print globals()['x'] 打印出的是 30 那么问题来了, 为什么`print locals()`是个空字典呢? 感觉是因为编译的时候?? local scope 被拿去占用了, 原来的被新生成的替代了. 执行完 exec 'print x' in globals(), locals()后, x 也消失了. 不知道楼主有没有什么新发现?? |
2
noobsheldon OP @daya0576
x = 30 exec_local = {'x': 100} def out(): x = 50 def inner(): print x print locals() exec 'print x' in globals(), exec_local print exec_local print x return inner out()() #===> 50 {} 100 {'x': 100} 50 |