python_day16_装饰器

装饰器基础写法

def outer(func):
    def inner():
        print("睡眠")
        func()
        print("起床")

    return inner


def sleep():
    import time
    print("睡眠中、、、")
    time.sleep(5)


f1 = outer(sleep)
f1()

python_day16_装饰器_第1张图片
python_day16_装饰器_第2张图片

装饰器语法糖

def outer(func):
    def inner():
        print("休息一下")
        func()
        print("结束休息")

    return inner  # 注意此处写法,无括号


@outer
def sleeping():
    import time
    print("休眠中....")
    time.sleep(5)


sleeping()

python_day16_装饰器_第3张图片
python_day16_装饰器_第4张图片
python_day16_装饰器_第5张图片

你可能感兴趣的:(python,python,开发语言)