来自 https://docs.python.org/3/reference/executionmodel.html#resolution-of-names
A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.
这里“在全局命名空间中查找未绑定(bind)的局部变量”是什么意思?一个类定义是否可以在另一个类定义或函数定义中,以便查找未绑定(bind)的局部变量不在全局命名空间中,而是在局部嵌套范围中?
什么是“正常规则”?
谢谢。
请您参考如下方法:
举个例子:
x = 1
def foo():
x = 2
class Bar:
print(x)
x = 3
foo()
# Output: 1
当 print() 被调用时,x 是本地的(因为它在下一行赋值),但仍然是未绑定(bind)的,因为它在赋值之前就被使用了。
您可能希望在最近的命名空间(即 2)中查找未绑定(bind)的 x,但在类 block 中,“未绑定(bind)的局部变量在全局命名空间中查找”,因此查找全局 x 并打印 1。
让我们删除 Bar 中的赋值:
x = 1
def foo():
x = 2
class Bar:
print(x)
foo()
# Output: 2
现在我们遵循“名称解析的正常规则”并得到输出2,因为里面的 不再是本地的(它是一个自由变量)并在最近的封闭范围内查找。x Bar
此外,在局部命名空间中查找未绑定(bind)局部变量的规则适用于类,而不适用于函数。让我们用一个函数试试:
x = 1
def foo():
x = 2
def bar():
print(x)
x = 3
bar()
foo()
# Raises: UnboundLocalError: local variable 'x' referenced before assignment
如您所见,在函数中,您不能在为局部变量赋值之前使用局部变量。
