这是我的代码:
def outer():
x = 0
d = { 'a' : 'b' }
def inner():
for _ in xrange(10):
x += 1
d['a'] = x
yield x
for y in inner():
print y
print "%d rounds" % (x)
outer()
给出了:
Traceback (most recent call last):
File "xxx.py", line 14, in <module>
outer()
File "xxx.py", line 11, in outer
for y in inner():
File "xxx.py", line 8, in inner
x += 1
UnboundLocalError: local variable 'x' referenced before assignment
如果我在x
中本地定义inner
,问题就会消失。换句话说:inner
不能修改外部定义的整数,但它可以修改字典。我想这是因为分配x
需要对它进行读/写访问,但是分配到字典不需要对字典的读/写访问:更新是对元素的字典?
如何实施inner
以便我可以访问并修改x
定义的变量outer
?