函数范围与方法

Scope in Functions vs. Methods

我想知道如果未定义名称,为什么 class 的方法不查看其封闭范围。

def test_scope_function():
    var = 5
    def print_var():
        print(var) # finds var from __test_scope_function__
    print_var()


globalvar = 5
class TestScopeGlobal:
    var = globalvar # finds globalvar from __main__

    @staticmethod
    def print_var():
        print(TestScopeGlobal.var)


class TestScopeClass():
    var = 5

    @staticmethod
    def print_var():
        print(var) # Not finding var, raises NameError

test_scope_function()
TestScopeGlobal.print_var()
TestScopeClass.print_var()

我希望 TestScopeClass.print_var() 打印 5,因为它可以在 TestScopeClass 正文中读取 classvar

为什么会出现这种行为?我应该在 docs 中阅读什么才能了解​​它。

搜索范围as follows:

  • the innermost scope, which is searched first, contains the local names
  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
  • the next-to-last scope contains the current module’s global names
  • the outermost scope (searched last) is the namespace containing built-in names

(强调)。不搜索包含 类 的内容,因为它们未列出。这种行为是故意的,因为否则 descriptor protocol,除其他外,为方法提供 self 参数,将没有机会触发。

根据 the Python documentation(强调我的):

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods