栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 闭包和装饰器

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 闭包和装饰器

1. 闭包 a. 闭包的条件

在Python中创建闭包必须满足的条件:

  • 我们必须有一个嵌套函数(函数在函数内部)。
  • 嵌套函数必须引用在封闭函数中定义的值。
  • 封闭函数必须返回嵌套函数。
b. 何时使用闭包?

闭包可以避免使用全局值,并提供某种形式的数据隐藏。它还可以为该问题提供面向对象的解决方案。

当在一个类中实现的方法很少(大多数情况下是一个方法)时,闭包可以提供另一种更优雅的解决方案。但是,当属性和方法的数量变大时,最好实现一个类。

def f(x):
    def g(y):
        return x + y
    return g  # Return a closure.

def h(x):
    return lambda y: x + y  # Return a closure.

# Assigning specific closures to variables.
a = f(1)
b = h(1)

# Using the closures stored in variables.
assert a(5) == 6
assert b(5) == 6

# Using closures without binding them to variables first.
assert f(1)(5) == 6  # f(1) is the closure.
assert h(1)(5) == 6  # h(1) is the closure.
2. 装饰器
from time import time, sleep


def runtime(f):
    def inner(*args, **kwargs):
        print(f'-- Function {f.__name__} start ...')
        t = time()
        result = f(*args, **kwargs)
        print(f'-- Function {f.__name__} end. (Runtime: {time() - t:.3f} seconds)n')
        return result

    return inner


@runtime
def func():
    sleep(2)


if __name__ == '__main__':
    func()

Output

-- Function func start ...
-- Function func end. (Runtime: 2.000 seconds)

参考资料:

[1] https://www.cainiaojc.com/python/python-closure.html

[2] https://en.wikipedia.org/wiki/Closure_(computer_programming)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942523.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号