gpt4 book ai didi

python - 如果我要使用一个变量,我必须总是在我的函数中将它引用为全局变量吗?

转载 作者:太空宇宙 更新时间:2023-11-04 07:17:45 25 4
gpt4 key购买 nike

首先,它与这个功能有关:

a = 3
def b():
a = a+1
return a

返回错误。

不就是b的本地环境找不到'a',然后去b所在的父环境> 被定义了,也就是发现'a'3

为什么我必须用 global a 引用它才能让它工作?意思是,只有当直接父环境是全局环境时我才必须这样做吗?因为下面的函数似乎可以引用父环境:

def b():
def c():
print c
return c()

最佳答案

这是一个很常见的问题,实际上在 Python FAQ 中。 :

[...] when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable.

因此,Python 看到您正在使用 a = .. 分配给一个局部变量,然后认为,嘿,一个局部变量,我对此没有意见。但是,当它实际遇到 该赋值的内容 (a + 1) 并看到相同的名称 a 时,它会提示,因为 您试图在分配它之前引用它

这就是以下不会引发错误的原因:

def b():
a = 20
a = a + 2
return a

您首先进行赋值,a 被视为函数 b 的局部,当遇到 a = a + 2 时,Python知道 a 是一个局部变量,这里没有混淆。


在另一种情况下,您添加了:

def b():
def c():
print c
return c()

您只是引用一个包含在函数b 范围内的名称,引用。如果您将此更改为与以前类似的分配,您将得到相同的 UnboundLocalError:

def b():
def c():
c = c + 20
return c()

关于python - 如果我要使用一个变量,我必须总是在我的函数中将它引用为全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com