• python 装饰器


    def works_for_all(func):
        def inner(*args, **kwargs):
            print("I can decorate any function")
            return func(*args, **kwargs)
        return inner

    例子一

    def make_pretty(func):
        def inner():
            print("I got decorated")
            func()
        return inner
    
    def ordinary():
        print("I am ordinary")

    执行

    >>> ordinary()
    I am ordinary
    
    >>> # let's decorate this ordinary function
    >>> pretty = make_pretty(ordinary)
    >>> pretty()
    I got decorated
    I am ordinary

    例子二

    def make_pretty(func):
        def inner():
            print("I got decorated")
            func()
        return inner
    
    @make_pretty
    def ordinary():
        print("I am ordinary")
    
    ordinary()

    输出

    I got decorated
    I am ordinary

    例子三

    def star(func):
        def inner(*args, **kwargs):
            print("*" * 30)
            func(*args, **kwargs)
            print("*" * 30)
        return inner
    
    def percent(func):
        def inner(*args, **kwargs):
            print("%" * 30)
            func(*args, **kwargs)
            print("%" * 30)
        return inner
    
    @star
    @percent
    def printer(msg):
        print(msg)
    printer("Hello")

    输出

    ******************************
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    Hello
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    ******************************

    上面的

    @star
    @percent
    def printer(msg):
        print(msg)

    相当于

    def printer(msg):
        print(msg)
    printer = star(percent(printer))

  • 相关阅读:
    软工实践-Alpha 冲刺 (7/10)
    软工实践-Alpha 冲刺 (6/10)
    软工实践-Alpha 冲刺 (5/10)
    软工实践-Alpha 冲刺 (4/10)
    BETA 版冲刺前准备
    第十一次作业
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10178572.html
Copyright © 2020-2023  润新知