- 不带参数的装饰器
def w1(main_func): def outer(*args, **kwargs): before_func(*args, **kwargs) #before_func定义忽略 main_func(*args, **kwargs) after_func(*args, **kwargs) #after_func定义忽略 return outer @w1 def show() pass # 装饰器w1将show作为其第一个参数,并使用返回值重新定义了show
- 带参数的装饰器
def login(name, password)... def errorHandler()... def Filter(before_func, after_func): def outer(main_func): def wrapper(*args, **kwargs): before_result = before_func(*args, **kwargs) main_result = main_func(*args, **kwargs) after_result = after_func(*args, **kwargs) return wrapper return outer @Filter(login, errorHandler) def show(): pass #先运行一次Filter(login, errorHandler),用返回值替换自身。然后再运行outer(main_func)