在 Python 中,cell 对象用于存储closure 的free variables。
假设您想要一个始终返回其参数的特定部分的函数。您可以使用闭包来实现:
def multiplier(n, d):
"""Return a function that multiplies its argument by n/d."""
def multiply(x):
"""Multiply x by n/d."""
return x * n / d
return multiply
你可以这样使用它:
>>> two_thirds = multiplier(2, 3)
>>> two_thirds(7)
4.666666666666667
two_thirds 如何记住n 和d 的值?它们不是multiplier 定义的multiply 函数的参数,它们不是在multiply 中定义的局部变量,它们不是全局变量,并且由于multiplier 已经终止,它的局部变量不再存在对吧?
当multiplier 被编译时,解释器注意到multiply 稍后将要使用它的局部变量,所以它会记录它们:
>>> multiplier.__code__.co_cellvars
('d', 'n')
然后当multiplier被调用时,那些外部局部变量的值被存储在返回函数的__closure__属性中,作为cell对象的元组:
>>> two_thirds.__closure__
(<cell at 0x7f7a81282678: int object at 0x88ef60>,
<cell at 0x7f7a81282738: int object at 0x88ef40>)
...在__code__ 对象中的名称为co_freevars:
>>> two_thirds.__code__.co_freevars
('d', 'n')
您可以使用它们的cell_contents 属性获取单元格的内容:
>>> {v: c.cell_contents for v, c in zip(
two_thirds.__code__.co_freevars,
two_thirds.__closure__
)}
{'d': 3, 'n': 2}
您可以在介绍闭包的 Python 增强提案中了解更多关于闭包及其实现的信息:PEP 227 — Statically Nested Scopes。