当前位置: 首页 > 图灵资讯 > 行业资讯> python自由变量是什么

python自由变量是什么

来源:图灵python
时间: 2024-07-30 10:01:31

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

defmake_averager():
count=0
total=0
defaverager(new_value):
count+=1
total+=new_value
returntotal/count
returnaverager


>>>avg=make_averager()
>>>avg(10)
Traceback(mostrecentcalllast):
...
UnboundLocalError:localvariable'count'referencedbeforeassignment

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

defmake_averager():
count=0
total=0
defaverager(new_value):
nonlocalcount,total#声明count、自由变量为total
count+=1
total+=new_value
returntotal/count
returnaverager

以上是python自由变量的介绍,希望对大家有所帮助。更多Python学习指导:python基础教程

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