码迷,mamicode.com
首页 > 编程语言 > 详细

python闭包

时间:2017-09-23 23:18:06      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:inter   属性   min   this   ogr   highlight   调用   pytho   other   

 1 def print_msg(msg):
 2 # This is the outer enclosing function
 3 
 4     def printer():
 5 # This is the nested function
 6         print(msg)
 7 
 8     printer()
 9 
10 # We execute the function
11 # Output: Hello
12 print_msg("Hello")

如上所示,printer是内嵌函数(nested function),根据LEGB的E原则,取到了传入的msg参数

def print_msg(msg):
# This is the outer enclosing function

    def printer():
# This is the nested function
        print(msg)

    return printer  # this got changed

# Now let‘s try calling this function.
# Output: Hello
another = print_msg("Hello")
another()

如果将print_msg内的printer调用替换成将其返回,赋值到变量another,print another会得到 : <function printer at 0x02666AB0>, 可见赋值给another的是执行后的print_msg的值,即 printer,那么another()即代表执行printer(),而此时printer()仍然可以记得msg的值,即使print_msg函数已经结束执行,或者在another=print_msg("hello")后将print_msg删除,del print_msg也无妨。

 

闭包必须包含:

  • 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.      enclosing函数返回嵌套函数

__closure__

closure属性返回一个包含cell的元组,里面每个cell保存了作用域变量

print another.__closure__

>>> (<cell at 0x024FC990: str object at 0x024FC960>,)

print another.__closure__[0].cell_contents

>>>Hello

参考:https://www.programiz.com/python-programming/closure

python闭包

标签:inter   属性   min   this   ogr   highlight   调用   pytho   other   

原文地址:http://www.cnblogs.com/tachikoma-/p/7582739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!