[TimLinux] Python nonlocal和global的作用

1. 执行代码

以下实例都是通过执行以下代码,需要把以下执行代码放在后面实例代码的后面。

a = outer_func()
print("call a()") a() a() a() b
= outer_func()
print("call b()") b() b() b()

2. 未使用nonlocal

def outer_func():
    count = 3
    def inner_func():
        count += 1
        print("count", count)
    return inner_func

#output>>>
#    count += 1
#UnboundLocalError: local variable 'count' referenced before assignment

3. 使用nonlocal

def outer_func():
    count = 3
    def inner_func():
        nonlocal count
        count += 1
        print("count", count)
    return inner_func

# output>>>
# call a()
# count 4
# count 5
# count 6

# call b()
# count 4
# count 5
# count 6

4. 使用global (出错)

def outer_func():
    count = 3
    def inner_func():
        global count
        count += 1
        print("count", count)
    return inner_func

# output>>>
#     count += 1
# NameError: name 'count' is not defined

5. 使用global (成功)

count = 3
def outer_func():
    def inner_func():
        global count
        count += 1
        print("count", count)
    return inner_func

# output>>>
# call a()
# count 4
# count 5
# count 6

# call b()
# count 7
# count 8
# count 9

猜你喜欢

转载自www.cnblogs.com/timlinux/p/9193222.html