1、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): ... 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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试