考虑这段代码:
def main():
l = []
def func():
l += [1]
func()
print(l)
if __name__ == '__main__':
main()
它将产生:
Traceback (most recent call last):
File "/Users/tahsmith/Library/Preferences/PyCharm2017.1/scratches/scratch_21.py", line 14, in <module>
main()
File "/Users/tahsmith/Library/Preferences/PyCharm2017.1/scratches/scratch_21.py", line 11, in main
func()
File "/Users/tahsmith/Library/Preferences/PyCharm2017.1/scratches/scratch_21.py", line 9, in func
l += [1]
UnboundLocalError: local variable 'l' referenced before assignment
这本身可以通过nonlocal l
在开头使用func
或__iadd__
直接使用而不是来解决+=
。
问题:这里为什么nonlocal
需要?
这对我来说非常令人惊讶。