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也无妨。
闭包必须包含:
__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
原文:http://www.cnblogs.com/tachikoma-/p/7582739.html