Python 代码对象有一个属性 co_cellvars
. PyPy's bytecode interpreter 的文档经常使用术语细胞。
在其他语言中,Rust provides a Cell datatype .谷歌搜索表明它们以某种方式与闭包有关。
在编程语言实现的上下文中,什么是单元?细胞解决什么问题?
最佳答案
在 Python 中,cell
对象用于存储 free variables的 closure .
假设您想要一个始终返回其参数的特定部分的函数。您可以使用闭包来实现这一点:
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 .
关于python - 在解释器或编译器的上下文中,单元格是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38681121/