current position:Home>Python notes (17): closure

Python notes (17): closure

2022-01-30 15:41:14 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~


The concept of closure in function , Simply put, a function definition refers to variables defined outside the function , And the function can be executed outside its definition environment . Such a function is called closure . In fact, closure can be seen as a more generalized concept of function . Because it is no longer a function defined in the traditional sense .

The concept of closure is not limited to Python in , In almost any programming language .

The condition of closure :

  1. The internal function is defined in the external function
  2. An external function has a return value
  3. The return value is : Internal function
  4. The inner function also references the variables of the outer function

The format is as follows :

def  External function ():
    def  Internal function ():
    return  Internal function 
 Copy code 

Sample code

def func():
    a = 100

    def inner_func():
        b = 200
        print(a, b)

    return inner_func

x = func()
print(x)  # <function func.<locals>.inner_func at 0x0000021704CD9620>
x()  # 100 200
#  So you can call it directly inner_func function , If return If you don't return an internal function, there will be no output 
 Copy code 

Using closures can also accomplish the effect of counters

def generate_count():
    container = [0]

    def add_one():
        container[0] += 1
        print(f" This is the first {container[0]} Secondary call ")

    return add_one

count = generate_count()
count()  #  This is the first 1 Secondary call 
count()  #  This is the first 2 Secondary call 
count()  #  This is the first 3 Secondary call 
 Copy code 

Closure shortcoming As shown below :

  1. The scope is not so intuitive
  2. Because variables will not be garbage collected, there is a certain memory occupation problem .

Closure effect As shown below :

  1. You can use peer scopes
  2. Read internal variables of other elements
  3. Extend scope

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.

Random recommended