栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

与语言X闭包相比,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_errorUnboundLocalError: 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/626167.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号