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自由变量的介绍,希望对大家有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。
下一篇