欢迎访问个人网络日志🌹🌹知行空间🌹🌹
1.通过函数定义装饰器
class MyObj:
def __init__(self, value):
self.value = value;
def set_value(self, value):
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(12)
o.get_set_value_name()
# 想在set_value之前打印一个日志
def log(f):
def w(*args, **kwargs):
print("begin to log")
return f(*args, **kwargs)
return w
class MyObj:
def __init__(self, value):
self.value = value;
@log # 等同于 set_value = log(set_value)
def set_value(self, value):
print(set_value.__name__)
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(120)
o.get_set_value_name()
# 定义带入参的装饰器
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
class MyObj:
def __init__(self, value):
self.value = value;
@log("MyObj") # 等同于 set_value = log('MyObj')(set_value)
def set_value(self, value):
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(120)
o.get_set_value_name()
# set_value的函数签名被修改了, 对于依赖函数签名的代码将报错
# 不需要编写wrapper.__name__ = func.__name__这样的代码
# 可使用Python内置的functools.wraps模块
# 定义带入参的装饰器
import functools
def log(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
class MyObj:
def __init__(self, value):
self.value = value;
@log("MyObj") # 等同于 set_value = log('MyObj')(set_value)
def set_value(self, value):
print("set value:",value)
self.value = value
def get_set_value_name(self):
print(self.set_value.__name__)
o = MyObj(10)
o.set_value(120)
o.get_set_value_name()
输出
set value: 12
set_value
begin to log
set_value
set value: 120
w
MyObj set_value():
set value: 120
wrapper
MyObj set_value():
set value: 120
set_value
2.定义装饰器类
# 装饰器类
class logit(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, func):
@functools.wraps(func)
def wrapped_function(*args, **kwargs):
log_string = func.__name__ + " was called"
print(log_string)
# 打开logfile并写入
with open(self.logfile, 'a') as opened_file:
# 现在将日志打到指定的文件
opened_file.write(log_string + '\n')
# 现在,发送一个通知
self.notify()
return func(*args, **kwargs)
return wrapped_function
def notify(self):
# 此时logit只打日志,不做别的,若需要发送通知只需要继承该类实现此方法即可
pass
@logit()
def do_nothing():
pass
do_nothing()
输出
do_nothing was called
参考资料
欢迎访问个人网络日志🌹🌹知行空间🌹🌹