首页 > 文章列表 > python自由变量是什么

python自由变量是什么

python自由变量
436 2022-08-07

1、自由变量是指未绑定到本地作用域的变量。如果自由变量绑定的值是可变的,变量仍然可以在封闭包中操作。如果是不可变的(数字、字符串等。),在封闭包中重新绑定自由变量会出错。

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):
...
UnboundLocalError: local variable 'count' referenced before assignment

2、为了将变量标记为自由变量,可以使用nonlocal语句进行声明,nonlocal语句可以解决。

def make_averager():
    count = 0
    total = 0
    def averager(new_value):
        nonlocal count, total   # 声明count、total为自由变量
        count += 1
        total += new_value
        return total / count
    return averager

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。