python闭包

发布时间 2023-08-08 10:02:56作者: steve.z
#
#   py_decorator.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/8 08:34.
#


# 装饰器:本质闭包。在不破坏原目标函数原来代码和功能的前提下,为目标函数增加新功能。
# 定义一个闭包函数, 在闭包函数内部执行目标函数,并完成功能添加


# 1. 装饰器的一般写法
def decorate(fn):
    def decorator_func():
        print("doing sth before......")
        fn()
        print("doing sth after......")

    return decorator_func


# 2. 装饰器的快捷写法(语法糖)
# 只需要在原函数上面加 @创建闭包的函数名  即可
# 然后直接调用原函数, 此时原函数调用时自动就封装闭包了


# 定义一个正在执行的函数
@decorate
def func():
    print("doing sth here.")


if __name__ == "__main__":
    # dfn = decorate(func)
    # dfn()
    func()