设为首页 加入收藏

TOP

python闭包
2017-09-30 13:02:43 】 浏览:7509
Tags:python 闭包
 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闭包 下一篇Python初识

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目