python简单进阶,closure

closure

we have a closure in Python when a nested function references a value in its enclosing scope.
就是说closure就是python中的嵌套函数使用了封闭环境中的值(该函数外面一层函数中的数值),嵌套函数能够使用封闭函数中的变量,如下:

def print_meg(msg):
    # this is outer enclosing function
    def printer():
        # this is nested function
        print(msg)
    printer()


print_meg("hello world")

执行结果

hello world

或者这样写

def print_msg_two(msg):
    def printer():
        print(msg)

    return printer

another = print_msg_two("hello world two")
another()
del print_msg_two
another()

执行结果

hello world two
hello world two

1、解释

根据上面的代码
This technique by which some data (“Hello”) gets attached to the code is called closure in Python.

This value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace.

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

  1. We must have a nested function (function inside a function).
  2. The nested function must refer to a value defined in the enclosing function.
  3. The enclosing function must return the nested function.

2、When to use closures? what are closures good for?

Closures can avoid the use of global values and provides some form of data hiding.
It can also provide an object oriented solution to the problem.
例子如下:

def make_multiplier_of(n):
    def multiplier(x):
        return x*n
    return multiplier

time3 = make_multiplier_of(3)

time5 = make_multiplier_of(5)

print(time3(9))
print(time5(9))
print(time3(time5(3)))

执行结果

27
45
45

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.

def make_multiplier_of(n):
    def multiplier(x):
        return x*n
    return multiplier

time3 = make_multiplier_of(3)

time5 = make_multiplier_of(5)

print(time3.__closure__[0].cell_contents)
print(time5.__closure__[0].cell_contents)
print(make_multiplier_of.__closure__)

执行结果

3
5
None
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值