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 @   树叶本子  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示