Python 提高篇(三):Python closures

一、定义一个Python Closure 函数

首先直接上菜,然后再聊

例一:define a closure function
def print_msg(msg):
    # This is the outer enclossing function

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

# call this function
another = print_msg('hello')
another()

输出结果:

hello

上面的 print_msg() 函数被调用,传入的参数为“hello”,这个返回的函数指向another。 在调用another() 函数时,信息仍会被记住,尽管已经执行完print_msg() 函数。这就是 closure。

##例二: del

del  print_msg
another()
print_msg('hello')

输出为:

hello
Traceback (most recent call last):
File “G:/Project/Learn_python3/Demo05/blog.py”, line 15, in
print_msg(‘hello’)
NameError: name ‘print_msg’ is not defined

这就说明,在enclosing function的值被记住了,当删除函数后,调用another()仍会有输出。

二:使用closure的条件?

  1. 我们必须得有内层函数;
  2. 内层函数需要调用外层函数的参数;
  3. 在外层函数需要返回内层函数

三、什么时候用 closure?

closure 有什么好处?
  1. 可以避免使用全局变量
  2. 提供数据隐藏的形式
例二: make_multipier_of()
def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier


times3 = make_multiplier_of(3)

times5 = make_multiplier_of(5)

print(times3(3))
print(times3(times5(2)))

运行结果:

9
30

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值