前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【python】闭包

【python】闭包

作者头像
keloli
发布2022-07-28 08:44:04
7900
发布2022-07-28 08:44:04
举报

ref

concept

  • nested function(内嵌函数): A function that is defined inside another function is known as a nested function.
  • non-local variables

When do we have closures?

As seen from the above example, we have a closure in Python when a nested function references a value in its enclosing scope.

The criteria that must be met to create closure in Python are summarized in the following points.

代码语言:javascript
复制
We must have a nested function (function inside a function).
The nested function must refer to a value defined in the enclosing function.
The enclosing function must return the nested function.

example

代码语言:javascript
复制
def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier


# Multiplier of 3
times3 = make_multiplier_of(3)

# Multiplier of 5
times5 = make_multiplier_of(5)

# Output: 27
print(times3(9))

# Output: 15
print(times5(3))

# Output: 30
print(times5(times3(2)))

others

  • 一般来说,当对象中只有一个方法时,这时使用闭包是更好的选择。
  • All function objects have a closure attribute that returns a tuple of cell objects if it is a closure function. Referring to the example above, we know times3 and times5 are closure functions. 所有函数都有一个 closure属性,如果这个函数是一个闭包的话,那么它返回的是一个由 cell 对象 组成的元组对象。cell 对象的cell_contents 属性就是闭包中的自由变量。
代码语言:javascript
复制
make_multiplier_of.__closure__
times3.__closure__
(<cell at 0x0000000002D155B8: int object at 0x000000001E39B6E0>,)

The cell object has the attribute cell_contents which stores the closed value.

代码语言:javascript
复制
times3.__closure__[0].cell_contents
3
 times5.__closure__[0].cell_contents
5
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-07-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ref
  • concept
  • example
  • others
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档