导语:
本文主要介绍了关于python自由变量是什么的相关知识,包括python中文变量,以及python不用定义变量吗这些编程知识,希望对大家有参考作用。
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电脑。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python中如何掌握闭包的使用?01/11
- ♥ python的输入功能是如何工作的?08/18
- ♥ 如何在python中使用卡方分布?09/23
- ♥ python中字典中的键是否必须是唯一的?10/28
- ♥ Python选择排序算法的性能分析10/11
- ♥ python中print函数输出中sep和end的区别08/27
内容反馈