Skip to content

Latest commit

 

History

History
49 lines (37 loc) · 1.2 KB

84 闭包中,怎么对数字、字符串、元组等不可变元素更新.md

File metadata and controls

49 lines (37 loc) · 1.2 KB

Python100

把Python知识点整理成100道习题,知识点来自两本书:Python基础教程(第3版)和流畅的Python,以后会定期加入更多的习题,大家帮忙点个赞哈,点赞越多,更新越快~

闭包中,怎么对数字、字符串、元组等不可变元素更新

我们知道,在闭包中,声明的变量是局部变量,局部变量改变的话会报错。

>>> def make_averager():
    count = 0
    total = 0
    def averager (new_value):
        count += 1
        total += new_value
        return total / count
    return averager

>>> avg = make_averager()
>>> avg(10)
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    avg(10)
  File "<pyshell#61>", line 5, in averager
    count += 1
UnboundLocalError: local variable 'count' referenced before assignment

为了解决这个问题,Python 3引入了 nonlocal 声明。它的作用是把变量标记为自由变量

>>> def make_averager():
    count = 0
    total = 0
    def averager (new_value):
        nonlocal count, total
        count += 1
        total += new_value
        return total / count
    return averager

>>> avg = make_averager()
>>> avg(10)
10.0