search
HomeBackend DevelopmentPython TutorialWhat is closure in Python? What are the applications?

The content of this article is about what is closure in Python? What are the applications? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Function as return value

Before introducing "closure", let's first understand the situation of function as return value.
In addition to receiving functions as parameters, higher-order functions can also return functions as result values. For example, in the decorator introduced before, functions are used as return values.

2. Closure

1. Conditions and effects of closure

What is closure?
When nesting another function within a function, closure may occur if the inner function refers to the variables of the outer function.
SoThe three conditions for closure generation (one is indispensable):

  • 1. An internal function must be nested

  • 2. The internal function must reference the variables of the external function

  • 3. The external function must return the internal function

So why should we try closures and what are their functions?

  • 1. Closures can obtain different results based on the local variables of external functions.

  • 2. After the closure is executed, the The current running environment can be maintained, and the execution result depends on the last running result of the function

2. Closure example

Chestnut 1: Find the sum of the sequence

>>> def calc_sum(*args):
...     ax = 0
...     for n in args:
...         ax = ax + n
...     return ax  # 返回变量
...
>>> calc_sum(1,2,3)
6

However, if you do not need to obtain the summation result immediately, but calculate it as needed in the subsequent code, what should you do?
We can not return the summation result, but return the summation function, as follows:

>>>def lazy_sum(*args):
...    def sum():            # sum()是内部函数,可以利用外部函数的参数
...        ax = 0
...        for n in args:    # sum()中使用外部函数的局部变量
...            ax = ax + n 
...        return ax
...    return sum            # 形成闭包,此时,*args保存在返回的函数中
...
>>>f = lazy_sum(1,3,5,7,9)
>>>f          # 此时返回的是求和函数
>>> f()       # 调用函数f()时,才真正计算求和的结果
25

Note:

The internal execution sequence of the lazy_sum() function, when executing f, runs At return sum, *args is stored in the return function, and what is returned is the sum() function. When executing f(), it is equivalent to executing sum() and includes *args.

When we call lazy_sun(), a new function will be returned every time. Even if the same parameters are passed in, the result of the f() call will not be affected.

Let’s verify the second point:

# 但是调用 f1() 与f2()的调用结果互不影响
>>> f1 = lazy_sum(1,3,5,7,9)
>>> f2 = lazy_sum(1,3,5,7,9)
>>> f1
<function>.sum at 0x013DD618>
>>> f2
<function>.sum at 0x02F92DF8>
>>> f1 == f2
False
>>> f1() == f2()
True
>>> f1()
25
>>> f2()
25
>>> id(f1())
1627215984
>>> id(f2())
1627215984</function></function>

Explanation: The positions of the return functions of f1 and f2 are different, so the return result of f1==f2 is False.
But it does not affect the final execution result. The execution results of f1() and f2() are both 25, and they can be viewed with id(), which points to the same area.

Chestnut 2:

def count():
    fs = []
    for i in range(1, 4):
        def f():         # 返回函数f()放在循环里
            return i*i
    fs.append(f)
    return fs
f1, f2, f3 = count()

The actual execution result is: f1=9 f2=9 f3=9
It may be a little different from what you actually thought ([1,4,9]) . Because the f() function is placed in the for loop, only when the loop ends, the execution result 9 of i=3 is finally returned.
So it is best not to reference any loop variables in the return function, or the amount that may change in the future. So how to modify it?

def count():
    def f(j):
        def g():
            return j*j      # 形成闭包
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f(i))      # 一个i值进入后,f(i)立刻被执行,并加入到fs中
    return fs

f1, f2, f3 = count()  # 返回函数g没有引用j

Final result: [1,4,9] That is, f1=1 f2=4 f3=

3. Anonymous function lambda

Definition: Anonymous function refers to a type of function or subroutine that does not need to define an identifier function name. Python allows you to create anonymous functions using the lambda keyword.

Syntax: lambda parameter: expression
Or lambda formal parameter 1,..., formal parameter n: function (formal parameter), input parameter 1,..., input parameter n

Note : 1. The lambda function can receive any number of parameters and return the value of a single expression;
2. The lambda cannot contain commands and cannot return more than one expression.

Advantages: 1. The process of defining functions can be omitted and the code can be streamlined;
2. Some abstract functions that will not be reused can be defined with lambda.

Example:

>>> list( map( lambda x: x*x ,[1,2,3] ) )
[1, 4, 9]

Where lamdba x : x*x implements: def f(x): return x*x Function.

  • You can assign an anonymous function to a variable and then use the variable to call the function. For example:

>>> f = lambda x:x*x  
>>> f(5) # 调用
>>> g = lambda x,y=2 : x*y
>>> g(2,4)
8
>>> g(2)    # 默认y=2
4
  • You can return anonymous functions as return values, for example:

return lambda x:x*x

The above is the detailed content of What is closure in Python? What are the applications?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function