[英]change value of local variable from function inside function
我有這樣的事情:
def a():
#do something
foo = 0
def b():
foo += 2
# do something
b()
#do something
a()
但它說
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a()
File "<pyshell#5>", line 7, in a
b()
File "<pyshell#5>", line 5, in b
foo += 2
UnboundLocalError: local variable 'foo' referenced before assignment
如何訪問foo
而不使其成為全球性的?
b
中對foo
的賦值使其成為局部變量,與a
中的同名變量無關。 使用nonlocal
語句來改變它。
def a():
#do something
foo = 0
def b():
nonlocal foo
foo += 2
# do something
b()
#do something
現在b
中的foo
與 a 中的foo
是同a
變量。 nonlocal
類似於global
,但使用最接近的封閉 scope 包含名稱foo
而不是直接跳轉到全局 scope。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.