gpt4 book ai didi

Python - 列表变量的范围

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

我希望更好地理解事情,为什么它在函数 fct 中没有将列表 c 声明为全局变量的情况下工作?变量 a 不也是这样吗?

def fct():
global a # have to declare this for "a" to work, but not for c[]
print(a,c) # by not declaring "a" as global, caused this to flag
# "accessing a without assignment", which I understand why,
# but why c[] needn't declaration
c[1]=5
a=234

c=[0,0]
a=11
fct()

最佳答案

好吧,这个问题可能需要一点解释。

PEP 3104指出:

In most languages that support nested scopes, code can refer to or rebind (assign to) any name in the nearest enclosing scope. Currently, Python code can refer to a name in any enclosing scope, but it can only rebind names in two scopes: the local scope (by simple assignment) or the module-global scope (using a global declaration).

这里有两件事你必须明白:

  • 绑定(bind):创建一个名称,为其绑定(bind)一个值。例如:>>> a=10创建一个变量 a 并为其赋值 10。

  • 重新绑定(bind):更改绑定(bind)到名称的值。例如:>>> a=10;a=5绑定(bind)值 10,然后将 5 重新绑定(bind)到“a”本身。

所以正如它明确指出的那样,它只能在本地范围内重新绑定(bind)名称。

例子:

def func():
a=5
print(a)
a=10
print("a in the program")
print(a)
print("a in func()")
func()

输出:

a in the program
10
a in func()
5

现在从 func() 中删除 a=5 ,你会得到:

a in the program
10
a in func()
10

发生的事情是 a 被发现是 10 并被打印出来。

现在这样做:

def func():
print(a)
a=5
a=10
print("a in the program")
print(a)
print("a in func()")
func()

你明白了:

UnboundLocalError: local variable 'a' referenced before assignment

如果在函数中给 a=5 会发生什么?

现在没有发生重新绑定(bind),而是创建了一个新的局部变量 a=5。

所以,

  • 如果您不在print 语句之后/之前编写a=5,默认情况下它只会打印全局变量a .

  • 但是,如果您在 print(a) 之前编写 a=5,它会创建一个局部变量 a 然后绑定(bind)(注意:不是重新绑定(bind)而是绑定(bind))值 5 到它。

  • 但是如果你在 print(a) 之后写 a=5 它会混淆你为什么要引用一个变量(局部变量 a)尚未创建。

However, because any assignment to a name implicitly declares that name to be local, it is impossible to rebind a name in an outer scope (except when a global declaration forces the name to be global).

因此,如果您使用 global a,则 print(a) 会愉快地将全局 a 打印为 10,然后创建一个新的局部变量 a=5 通过将 5 绑定(bind)到 a。

global a
print(a)
a=5
print(a)

输出:

def func():
global a
print(a)
a=5
print(a)
a=10
print("a in the program")
print(a)
print("a in func()")
func()

但是对于您的其他对象,如 listdict 等,情况并非如此。在这种情况下,您只是在修改一个现有的全局对象,它是通过常规名称查找找到的(更改列表条目就像调用列表中的成员函数,它不是名称重新绑定(bind))。

所以它工作正常,没有任何错误。希望您有所了解。

关于Python - 列表变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44498847/

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