带参数的装饰代码示例
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())