考虑以下python代码片段:
x = 1
class Foo:
x = 2
def foo():
x = 3
class Foo:
print(x) # prints 3
Foo.foo()
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,这会打印 3。但是,如果我们在上面的代码片段中添加一行,行为就会改变:
x = 1
class Foo:
x = 2
def foo():
x = 3
class Foo:
x += 10
print(x) # prints 11
Foo.foo()
Run Code Online (Sandbox Code Playgroud)
而且,如果我们在上面的例子中切换两行的顺序,结果又会发生变化:
x = 1
class Foo:
x = 2
def foo():
x = 3
class Foo:
print(x) # prints 1
x += 10
Foo.foo()
Run Code Online (Sandbox Code Playgroud)
我想了解为什么会发生这种情况,更一般地说,了解导致这种行为的范围规则。根据 LEGB 范围规则,我希望两个片段都打印 3、13 和 3,因为x在封闭函数中定义了一个foo()。