Closure
In Python, a function is also an object. Therefore, when we define a function, we can define another nested function and return the nested function, for example:
from math import pow def make_pow(n): def inner_func(x): # 嵌套定义了 inner_func return pow(x, n) # 注意这里引用了外部函数的 n return inner_func # 返回 inner_func
In the above code, the function make_pow defines an inner function inner_func, and then Return this function. Therefore, we can use make_pow to generate another function:
>> > pow2 = make_pow(2) # pow2 是一个函数,参数 2 是一个自由变量 >> > pow2 <function inner_func at 0x10271faa0 > >> > pow2(6) 36.0
We also noticed that the inner function inner_func refers to the free variable n of the outer function make_pow, which means that when the life cycle of the function make_pow ends Afterwards, the variable n will still be saved in inner_func, which is referenced by inner_func.
>> > del make_pow # 删除 make_pow >> > pow3 = make_pow(3) Traceback(most recent call last): File "<stdin>", line 1, in < module > NameError: name 'make_pow' is not defined >> > pow2(9) # pow2 仍可正常调用,自由变量 2 仍保存在 pow2 中 81.0
---|---
Like the above situation, a function returns an internal function, which refers to the relevant parameters and variables of the external function. We put the The returned inner function is called a closure.
In the above example, inner_func is a closure that refers to the free variable n.
The role of closure
-
The biggest feature of closure is that it references free variables. Even if the environment that generated the closure has been released, the closure still exists;
A closure can have multiple instances at runtime, even if the parameters passed in are the same, for example:
>> > pow_a = make_pow(2) >> > pow_b = make_pow(2) >> > pow_a == pow_b False
Use closure Packages, we can also mock instances of classes.
Construct a class here to find the distance from one point to another:
from math import sqrt class Point(object): def __init__(self, x, y): self.x, self.y = x, y def get_distance(self, u, v): distance = sqrt((self.x - u) ** 2 + (self.y - v) ** 2) return distance >> > pt = Point(7, 2) # 创建一个点 >> > pt.get_distance(10, 6) # 求到另一个点的距离 5.0
Use closure to implement:
def point(x, y): def get_distance(u, v): return sqrt((x - u) ** 2 + (y - v) ** 2) return get_distance >> > pt = point(7, 2) >> > pt(10, 6) 5.0
As you can see, the result is the same, but using closures is more concise than using classes.
Common Misunderstandings
The concept of closure is very simple, but it is prone to some misunderstandings in its implementation, such as the following example:
def count(): funcs = [] for i in [1, 2, 3]: def f(): return i funcs.append(f) return funcs
In this example, we A function is created in the for loop and stored in funcs. Now, when calling the above function, you may think that the return result is 1, 2, 3, but in fact it is not:
>> > f1, f2, f3 = count() >> > f1() 3 >> > f2() 3 >> > f3() 3
Why? The reason is that the above function f refers to the variable i, but the function f is not executed immediately. When the for loop ends, the value of the variable i is 3, and the variables referenced by the functions in funcs are all 3, and the final result is all 3.
Therefore, we should try to avoid referencing loop variables in closures, or variables that will change subsequently.
How to solve the above situation? We can create another function and pass the value of the loop variable to the function, as follows:
def count(): funcs = [] for i in [1, 2, 3]: def g(param): f = lambda: param # 这里创建了一个匿名函数 return f funcs.append(g(i)) # 将循环变量的值传给 g return funcs >> > f1, f2, f3 = count() >> > f1() 1 >> > f2() 2 >> > f3() 3
Summary
A closure is a function that carries free variables, even if When the life cycle of the external function that created the closure ends, the free variables referenced by the closure still exist.
A closure can have multiple instances at runtime.
Try not to reference loop variables in closures, or variables that will change later.
The above is the content of Python advanced: closure carrying state. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
