All is well 3 idiots

AC小小常

【Python面向对象】(6) 装饰器(decorator)

1. 用于拓展原来函数功能的一种函数

2. 返回函数的一种函数

3. 在不用更改原函数代码的前提下给函数添加新的的功能

(1)没有装饰器时的实现

"""
不用装饰器的情况
"""


def hello():
    print("hello...")


def test():
    print("test...")


def hello_wrapper():
    print("开始hello函数...")
    hello()
    print("结束hello函数...")


def test_wrapper():
    print("开始test函数...")
    test()
    print("结束test函数...")


if __name__ == "__main__":
    # 其实这两个函数的构造都差不多,但是分为了两个方法来书写,代码的重用度不够
    hello_wrapper()
    # 输出:
    # 开始hello函数...
    # hello...
    # 结束hello函数...
    test_wrapper()
    # 输出:
    # 开始test函数...
    # test...
    # 结束test函数...

(2)装饰器下的实现

"""
用装饰器实现
"""


def log_in(func):
    """ 记录操作日志(英文) """
    def wrapper():
        print("start...")
        func()
        print("end...")
    return wrapper


def log_out(func):
    """ 记录操作日志(中文) """
    def wrapper():
        print("开始执行...")
        func()
        print("结束执行...")
    return wrapper


# 使用1个装饰器
@log_in
def hello():
    print("hello...")


# 使用2个装饰器
@log_out
@log_in
def test():
    print("test...")


if __name__ == "__main__":
    hello()
    # 输出:
    # start...
    # hello...
    # end...
    test()
    # 输出:
    # 开始执行...
    # start...
    # test...
    # end...
    # 结束执行...

 

posted on 2020-04-15 16:22  AC小小常  阅读(128)  评论(0编辑  收藏  举报

导航