这两个例子中`nonlocal`声明的变量都不存在吗?

时间:2017-09-08 02:52:13

标签: python python-3.x

在以下两个示例中,nonlocal声明的变量不存在是否正确?

那么为什么第一个例子中有错误,而第二个例子中没有错误?感谢。

示例1:

count = 0

def make_counter():
    def counter():
        nonlocal count  # SyntaxError: no binding for nonlocal 'count' found
        count += 1
        return count
    return counter

示例2:

a = 5

def f():
    a=2
    class C1:
        a = 3
        def f1(self):
            nonlocal a  # refers to `a` local to `f`
            a = 4
        def f2(self):
            self.f1()
            print(self.a)
    print(a)

f()  # 2
print(a)  # 5

1 个答案:

答案 0 :(得分:0)

每个python文档:https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement

nonlocal查找最近的封闭范围。在示例1中,您有:

count = 0 # global scope

def make_counter():
    # nonlocal scope
    def counter():
        # nonlocal scope, count references something in the global scope
        nonlocal count
        count += 1
        return count
    return counter

count是两个"范围级别"离开并且也位于global范围内,因此nonlocal会抛出语法错误,因为它不在nonlocal范围内。

在示例2中:

a = 5 # global scope

def f():
    # nonlocal scope
    a=2 # "a" referenced in nonlocal scope!
    class C1:
        # nonlocal scope
        a = 3 # "a" referenced in nonlocal scope!
        def f1(self):
            # local scope
            # "a" most recently referenced in nearest enclosing scope, no syntax error!
            nonlocal a
            a = 4
        def f2(self):
            self.f1()
            print(self.a)
    print(a)

f()  # 2
print(a)  # 5

由于示例2中的a在相邻的nonlocal范围内被引用,因此它不会引发错误。