Home  >  Article  >  Backend Development  >  Python Advanced: Closures Carrying State

Python Advanced: Closures Carrying State

黄舟
黄舟Original
2017-02-07 17:25:561107browse

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 &#39;make_pow&#39; 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)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn