day8-装饰器

装饰器:
没有改变调用方式和地址,并添加新的函数功能
1.无参数
2.有参数
3.多个装饰器装饰同一个函数
先执行最外层的装饰器


单个装饰器语言组织:


def timer(func):                       #1.装饰器加载到内存
    def deco():                         #
        print("sfd")                   #4.执行内容
        func()                 #5.func = test,并执行
    return deco                         #7.返回deco函数


@timer                        #2.test函数作为参数传进timer装饰器
def test(): #8                #
    print("test is running!")           #6.执行内容
test()                         #3.执行test() ,跳转到新的test()




多个装饰器:




def timer_0(func): #2.调入内存
    def deco(): #3.执行deco
        print("timer_0") #4.执行内容
        func() #5.func = test ,并跳转到timer_1装饰器,把@timer_1看成一个整体
    return deco #


def timer_1(func): #
    def deco(): #
        print("timer_1") #6.执行内容
        func() #7.func = test ,并跳转到test()
        print("timer_2") #10.执行内容
    return deco #


@timer_0 #1.执行装饰器timer_0
@timer_1 #
def test(): #8 #
    print("test is running!") #8.执行内容
test() #

猜你喜欢

转载自blog.csdn.net/tang12060/article/details/80595068