【发布时间】:2020-09-24 06:30:02
【问题描述】:
代码 1:for 循环
def foo():
one = '1'
two = '2'
three = '3'
d = {}
for name in ('one', 'two', 'three'):
d[name] = eval(name)
print(d)
foo()
输出:
{'一':'1','二':'2','三':'3'}
代码 2:听写理解
def foo():
one = '1'
two = '2'
three = '3'
print({name: eval(name) for name in ('one', 'two', 'three')})
foo()
输出:
NameError: name 'one' 未定义
代码3:添加全局关键字
def foo():
global one, two, three # why?
one = '1'
two = '2'
three = '3'
print({name: eval(name) for name in ('one', 'two', 'three')})
foo()
输出:
{'一':'1','二':'2','三':'3'}
字典推导和生成器推导创建自己的本地范围。根据闭包的定义(或者这里不是闭包),但是为什么Code 2不能访问外部函数foo的变量one[,two,three]呢?但是,代码3可以通过将变量one[,two,three]设置为全局来成功创建字典?
是不是因为eval 函数和dict 理解有不同的作用域?
希望有人帮助我,我将不胜感激!
【问题讨论】:
标签: python-3.x scope global-variables dictionary-comprehension