hbirthday 发表于 7 天前

python全局变量问题

def outter():
    def innerA():
      x = 100
   
    def innerB():
      nonlocal x
      x = 250
   
    def innerC():
      global x
      x = 520
   
    x = 880
   
    innerA()
    print(f"调用完 innerA() 函数之后,x = {x}")
   
    innerB()
    print(f"调用完 innerB() 函数之后,x = {x}")
   
    innerC()
    print(f"调用完 innerC() 函数之后,x = {x}")
   
outter()
print(f"此时此刻,全局变量 x = {x}")


调用完 innerA() 函数之后,x = 880
调用完 innerB() 函数之后,x = 250
调用完 innerC() 函数之后,x = 250
此时此刻,全局变量 x = 520

这条题目中的innerC函数是X=250,全局变量是X=250.
理解不了。
innerC使用了global是修改了全局变量,可是全局变量此刻是多少,为什么是250,而不是520呢?
最后的全局变量x=250,也是因为innerC这边使用了global而变化了吗?

FishC 发表于 7 天前

这个问题涉及到 Python 中的作用域和变量声明。我来帮你一步步分析:

首先,在 outter() 函数中,x = 880 定义的是一个局部变量,它属于 outter 的函数作用域。

现在来看三个内部函数:


[*] innerA() 中 x = 100 创建了一个新的局部变量,它不会影响 outter 中的 x,所以调用后 outter 的 x 还是 880。
[*] innerB() 使用 nonlocal x 声明要修改外层(即 outter)的 x,所以 x = 250 修改了 outter 的 x,此时 outter 的 x 变为 250。
[*] innerC() 使用 global x 声明要修改全局作用域的 x,所以 x = 520 修改的是全局变量 x,而不是 outter 的局部变量 x。因此,调用后 outter 的 x 仍然是 250,而全局变量 x 被设置为 520。


所以,最后的输出结果是:
调用完 innerA() 函数之后,x = 880
调用完 innerB() 函数之后,x = 250
调用完 innerC() 函数之后,x = 250
此时此刻,全局变量 x = 520

你提到的“innerC函数是X=250,全局变量是X=250”可能是误解。实际上,在 innerC 中修改的是全局变量,但打印的是 outter 的局部变量,所以显示 250。而最后的全局变量是 520。

简单总结:

[*] nonlocal 修改外层函数的变量
[*] global 修改全局变量
[*] 不加声明则创建新的局部变量


以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: python全局变量问题