关于python:函数与方法的范围

Scope in Functions vs. Methods

本问题已经有最佳答案,请猛点这里访问。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

为什么会这样?我应该在医生那里读些什么来了解它。


搜索范围如下:

  • 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

(增加了重点)。不搜索封闭类,因为它们未列出。这种行为是故意的,因为描述符协议(除其他外,它为方法提供self参数)将没有机会触发。


根据python文档(emphasis mine):

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