1、自定义装饰器使用写法及示例代码
2、一个函数方法使用两个装饰器
文档:https://docs.python.org/3/reference/compound_stmts.html#function
from functools import wraps
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
@makebold
@makeitalic
def log(s):
return s
print hello() # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello') # returns "<b><i>hello</i></b>"
相关文档:
Python内置装饰器(@property、@staticmethod、@classmethod)使用及示例代码
Python中@staticmethod和@classmethod区别及使用示例代码