gpt4 book ai didi

python - "local variable referenced before assignment"——只有功能?

转载 作者:太空狗 更新时间:2023-10-29 18:05:02 25 4
gpt4 key购买 nike

采用以下代码:

import something

def Foo():
something = something.SomeClass()
return something

...这显然不是有效代码:

UnboundLocalError: local variable 'something' referenced before assignment

...因为局部变量 something 被创建,但没有赋值,在 = 的 RHS 被评估之前。 (例如,请参见 this related answer's comment。)这对我来说似乎有点奇怪,但可以肯定的是,我会接受它。现在,为什么下面的代码有效?

class Foo(object):
something = something.SomeClass()

我的理解是 class 定义的内部本质上是一个范围:

The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace.

那么,为什么该代码的行为与函数的行为不同?

最佳答案

来自python class documentation :

Class definitions place yet another namespace in the local scope.

A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement del x removes the binding of x from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope. (The global statement can be used to indicate that particular variables live in the global scope.)

所以在函数(或作用域)内,赋值创建一个局部未绑定(bind)变量,在绑定(bind)之前访问该变量,而在类定义中,它在赋值时在该类的“命名空间”字典中创建一个条目,允许将 something 解析为外部命名空间(模块命名空间)。

关于python - "local variable referenced before assignment"——只有功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9088676/

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