在同一范围(Python)中其他函数中函数范围中的修改变量

发布于 2025-02-13 13:50:23 字数 357 浏览 3 评论 0原文

我有一个变量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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

⊕婉儿 2025-02-20 13:50:23

您必须将全局替换为非局部

You must replace global to nonlocal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文