gpt4 book ai didi

python - 与语言 X 闭包相比,Python 中的闭包有哪些限制?

转载 作者:IT老高 更新时间:2023-10-28 20:35:34 25 4
gpt4 key购买 nike

其中 X 是任何支持某种闭包风格的编程语言(C#、Javascript、Lisp、Perl、Ruby、Scheme 等)。

Closures in Python 中提到了一些限制。 (与 Ruby 的闭包相比),但这篇文章已经过时,现代 Python 中不再存在许多限制。

查看具体限制的代码示例会很棒。

相关问题:

最佳答案

目前最重要的限制是您不能分配给外部范围变量。换句话说,闭包是只读的:

>>> def outer(x): 
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', not the outer 'x'
... x = y
... def inner_error(y):
... # Will produce an error: 'x' is local because of the assignment,
... # but we use it before it is assigned to.
... tmp = x
... x = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
5
>>> inner_error(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner_error
UnboundLocalError: local variable 'x' referenced before assignment

除非另有声明,否则在本地范围(函数)中分配的名称始终是本地的。虽然有一个“全局”声明来声明一个全局变量,即使它被分配给它,但对于封闭的变量,还没有这样的声明。在 Python 3.0 中,有(将有)'nonlocal' 声明可以做到这一点。

您可以同时使用可变容器类型来解决此限制:

>>> def outer(x):
... x = [x]
... def inner_reads():
... # Will return outer's x's first (and only) element.
... return x[0]
... def inner_writes(y):
... # Will look up outer's x, then mutate it.
... x[0] = y
... def inner_error(y):
... # Will now work, because 'x' is not assigned to, just referenced.
... tmp = x[0]
... x[0] = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
10
>>> inner_error(15)
10
>>> inner_reads()
15

关于python - 与语言 X 闭包相比,Python 中的闭包有哪些限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/141642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com