python 函数装饰器

# 函数传入的参数可以是函数

def func1():
    print('1')

def func2(func):  # func为函数
    func()
    print('2')

func2(func1)  # 1 2

 

def func1(func):
    def call():
        print('----start----')
        func()
        print('----end----')
    return call

def func2():
    print('here is the func2')
    
@func1  # 将func3作为一个参数放入func1中再调用
def func3():
    print('here is the func3')

myfunc1 = func1(func2)
myfunc1()

myfunc2 = func3()
mufunc2()  # 同样的效果

 

并且可以存在多个装饰器,且装饰器可以带参数(只需要多嵌套一层即可)

def func1(name):
    def call1(func):
        def call2():
            print(f'my name is {name}')
            print('----start----')
            func()
            print('----end----')
        return call2
    return call1

@func1(name='xxp')
def func2():
    print('here is the func2')

 

posted @ 2022-11-08 15:34  树叶本子  阅读(23)  评论(0)    收藏  举报