带参数的装饰代码示例

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())
posted @ 2019-07-03 22:39  公众号python学习开发  阅读(164)  评论(0编辑  收藏  举报