欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python简单进阶,closure

程序员文章站 2022-06-22 23:03:01
closurewe 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():...

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

本文地址:https://blog.csdn.net/qq_40666620/article/details/107898205

相关标签: python进阶