A brief introduction to closures in Python (with examples)

不言
Release: 2018-10-10 15:45:15
forward
2533 people have browsed it

This article brings you a brief introduction to closures in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1: Introduction
Functional programming is not necessary for programs, but it plays an important role in simplifying programs.
Everything in Python is an object, and functions are also objects

   a = 1
    a = 'str'
    a = func
Copy after login

2: Closure

A closure is an entity composed of a function and its related reference environment ( That is: closure = function environment variable)
If in an inner function, a variable in the outer scope (but not in the global scope) is referenced, then the inner function is considered a closure, This is the most straightforward explanation! And the value of this variable will not be modified by the same variable value in the module!

3: The role of closure

Use less global variables. Closure can avoid using global variables
You can call the value inside the function from outside the function:
print(f .__closure__[0].cell_contents)
# Return the value of the environment variable in the closure!
Module operation is not possible!

# ----------------------------------------------#
# 闭包
# ----------------------------------------------#
# 函数内部定义函数
def curve_pre():
    def curve():
        print("抛物线")
        pass
    return curve
# 不能直接调用函数内部的函数
# curve()
func = curve_pre()
func()
def curve_pre1():
    a = 25  # 环境变量a的值在curve1外部

    def curve1(x):
        print("抛物线")
        return a * x ** 2
    return curve1       # 返回了的闭包
f = curve_pre1()
result = f(2)
print(result)
# 当在外部定义变量的时候,结果不会改变
a = 10
print(f(2))
print(f.__closure__)    # 检测函数是不是闭包
print(f.__closure__[0].cell_contents)    # 返回闭包中环境变量的值!
# ----------------------------------------------#
# 闭包的实例
# ----------------------------------------------#
def f1():
    m = 10
    def f2():
        m = 20  # 局部变量
        print("1:", m)  # m = 20
    print("2:", m)      # m = 10
    f2()
    print("3:", m)      # m = 10,臂包里面的值不会影响闭包外面的值
    return f2
f1()
f = f1()
print(f.__closure__)    # 判断是不是闭包

# ----------------------------------------------#
# 闭包解决一个问题
# ----------------------------------------------#
# 在函数内部修改全局变量的值计算某人的累计步数
# 普通方法实现
sum_step = 0


def calc_foot(step=0):
    global sum_step
    sum_step = sum_step + step


while True:
    x_step = input('step_number:')
    if x_step == ' ':   # 输入空格结束输入
        print('total step is ', sum_step)
        break
    calc_foot(int(x_step))
    print(sum_step)

# 闭包方式实现----->少使用全局变量,闭包可以避免


def factory(pos):

    def move(step):
        nonlocal pos    # 修改外部作用域而非全局变量的值
        new_pose = pos + step
        pos = new_pose  # 保存修改后的值
        return pos

    return move


tourist = factory(0)
print(tourist(2))
print(tourist(2))
print(tourist(2))
Copy after login

The above is the detailed content of A brief introduction to closures in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!