'''类装饰器 --- 装饰器的实现方法为 魔术方法 __call__()装饰器传递参数无参类装饰器有参类装饰器
'''# 1.类装饰器传递参数
class log:#通过构造方法传递原函数def __init__(self,func):self.func = func#实现装饰器的魔术方法def __call__(self,*args,**kwargs):print("log-------before")self.func(*args,**kwargs)print("log--------after")@log
def add_user():print("add user")add_user()# 2.无参类的装饰器
class no_args_log:#通过构造方法传递原函数def __init__(self,func):self.func = func#实现装饰器的魔术方法def __call__(self,*args,**kwargs):print("log-------before")self.func(*args,**kwargs)print("log--------after")@no_args_log
def add_user():print("无参类装饰器")add_user()# 3.有参类的装饰器 !!!不再使用构造方法传递原函数,选哟传递装饰器的参数
class args_log:#通过构造方法传递原函数def __init__(self,operator,time):self.operator = operatorself.time = time#实现装饰器的魔术方法 --- 调用原函数时,不需要使用selfdef __call__(self,func):def wrapper(*args,**kwargs):print(f"log --- before : {operator} - {time}")func(*args,**kwargs)print(f"log --- after : {operator} - {time}")return wrapperimport time
operator = "王兆玮"
time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())@args_log(operator,time)
def add_user(username):print(f"add user: {username}")
add_user("尹书婷")