zl程序教程

您现在的位置是:首页 >  其他

当前栏目

带参数的装饰代码示例

代码 参数 示例 装饰
2023-09-14 09:06:35 时间
def tag(name="div",title=None):
    def _tag(func):
        def deco(*args,**kwargs):
           result = None
           if title is None:
               result = f"<{name}>"+func(*args,**kwargs)+f"</{name}>"
           else:   
               result = f"<{name} class='{title}'>"+func(*args,**kwargs)+f"</{name}>"
           return result 
        return deco
    return _tag    

@tag(name="h1",title="say")
def foo(msg):
    return "hello world"

@tag()
def hello():
    return "hehe"

print(foo("abc"))
print(hello())

通过第三方包wrapt简单的修改下:

import wrapt

def tag(name="div",title=None):
    @wrapt.decorator
    def _tag(wrapped, instance, args, kwargs):
           result = None
           if title is None:
               result = f"<{name}>"+wrapped(*args,**kwargs)+f"</{name}>"
           else:   
               result = f"<{name} class='{title}'>"+wrapped(*args,**kwargs)+f"</{name}>"
           return result 
    return _tag 

@tag(name="h1",title="say")
def foo(msg):
    return "hello world"

@tag()
def hello():
    return "hehe"

print(foo("abc"))
print(hello())