python 闭包 nonlocal 变量作用域

'''
#count 出现在等号左边,
程序认为他是局部变量,和外部的同名变量是两个变量。
因此需要:
1    nonlocal相当于以前接触过的global,让系统认为内外同名
     变量为同一个变量,即nonlocal可以理解为global内层的小global
2    通过把变量放入列表,使得内层嵌套的def中的count不会出现在等号左边作为变量名
     对象list1[0]为此时的变量名。因此会认为count在内层不存在,接着在外层寻找

'''
def make_averager():
#nonlocal不仅可以帮助获取,还能帮助修改外层变量
    count = 0
    total = 0
    def averager(new_value):
        nonlocal count,total
        count += 1
        total += new_value
        return int(total / count)
    return averager

print(make_averager()(10))
>>>10
################
#列表只能帮助获取外层变量
def make_averager():
    total = 7
    list1 = [total]
    def averager(new_value):
        list1[0] += new_value
        return total,list1[0]
    return averager

print(make_averager()(2))
>>>(7,9)

参考网址:https://www.jianshu.com/p/17a9d8584530(转载)

猜你喜欢

转载自blog.csdn.net/qq_35515661/article/details/81255098