首页 > 编程语言 > 详细

[TimLinux] Python nonlocal和global的作用

时间:2018-06-17 17:13:56      阅读:238      评论:0      收藏:0      [点我收藏+]

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

 

[TimLinux] Python nonlocal和global的作用

原文:https://www.cnblogs.com/timlinux/p/9193222.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!