[英]How to define a free variable
I am currently reading the book Fluent Python - Luciano Ramalho (a great book IMO).我目前正在阅读这本书 Fluent Python - Luciano Ramalho(IMO 的一本好书)。
In the chapter about decorators and closures, there is a following piece of code:在关于装饰器和闭包的章节中,有一段代码如下:
def make_averager():
series = []
def averager(value):
series.append(value)
total = sum(series)
return total/len(series)
return averager
avg = make_averager()
So in this case, series
is a free variable, and I can verify this by printing所以在这种情况下, series
是一个自由变量,我可以通过打印来验证这一点
>>> avg.__code__.co_varnames
('new_value', 'total')
>>> avg.__code__.co_freevars
('series',)
But when I tried refactoring the make_averager()
:但是当我尝试重构make_averager()
时:
def make_averager():
series = []
total = 0
count = 0
def averager(value):
total += value
count += 1
return total/count
return averager
avg = make_averager()
either series
, total
or sum
is considered a free_variable. series
、 total
或sum
都被视为 free_variable。 Instead, total
and sum
are now local variables (?) since avg.__code__.co_varnames
returns ('value', 'total', 'count')
and avg.__code__.co_freevars
returns ()
.相反, total
和sum
现在是局部变量 (?),因为avg.__code__.co_varnames
返回('value', 'total', 'count')
和avg.__code__.co_freevars
返回()
。
So now series
is now no longer a free-variable in the scope of averager
, unless I add所以现在series
现在不再是averager
的 scope 中的自由变量,除非我添加
series.append(value)
inside averager(value)
.内部averager(value)
。 This is understandable since I don't call series
at all inside averager(value)
, but I couldn't understand what's happening with those 2 variables.这是可以理解的,因为我根本没有在averager(value)
内部调用series
,但我无法理解这两个变量发生了什么。
Why are total
and count
not considered as free-variables, and how do I assign them as free-variables?为什么total
count
不被视为自由变量,我如何将它们分配为自由变量?
def averager(value):
nonlocal total
nonlocal count
total += value
count += 1
return total/count
Without nonlocal, total += value
assigns to total
which by default creates a local variable.如果没有 nonlocal, total += value
会分配给total
,默认情况下会创建一个局部变量。 Since total
is in the local scope of the function averager
, it is no longer a free variable.由于total
在 function averager
的本地 scope 中,它不再是一个自由变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.