在同一范围(Python)中其他函数中函数范围中的修改变量
我有一个变量a
,其范围在功能f()
中。 在f()
的范围中,还有另一个函数b()
,其中变量a
正在修改。如何确保变量在函数b()
中修改,并在函数范围f()
的范围中正确反映?
def f():
a = 1
def b():
global a
a = 2
b()
print(a)
f()
>>> 1 # expected is 2
I have a variable a
whose scope is in function f()
.
There is another function b()
in the scope of f()
, where variable a
is getting modified. How can I make sure the variable gets modified in function b()
and is reflected correctly in the scope of function f()
?
def f():
a = 1
def b():
global a
a = 2
b()
print(a)
f()
>>> 1 # expected is 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将
全局
替换为非局部
。You must replace
global
tononlocal
.