【问题标题】:Scope in Functions vs. Methods [duplicate]函数与方法的范围[重复]
【发布时间】:2015-04-25 02:01:48
【问题描述】:

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

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 中阅读什么来了解它。

【问题讨论】:

    标签: python python-3.x scope


    【解决方案1】:

    搜索范围as follows:

    • 最里面的范围,首先搜索,包含本地名称
    • 从最近的封闭范围开始搜索的任何封闭函数的范围包含非本地名称,但也包含非全局名称
    • 倒数第二个范围包含当前模块的全局名称
    • 最外层范围(最后搜索)是包含内置名称的命名空间

    (强调添加)。不搜索封闭类,因为它们没有列出。这种行为是故意的,因为否则descriptor protocol(其中包括为方法提供self 参数)将没有机会触发。

    【讨论】:

      【解决方案2】:

      每个the Python documentation(强调我的):

      类块中定义的名称范围仅限于类块;它不会扩展到方法的代码块

      【讨论】:

        猜你喜欢
        • 2011-11-19
        • 2011-08-22
        • 2020-12-28
        • 2011-03-01
        • 1970-01-01
        • 2013-06-05
        • 2016-07-11
        • 2018-07-02
        • 2013-04-19
        相关资源
        最近更新 更多