類也可以用來構建裝飾器;
現在以一個類而不是一個函數的方式,來重新構建logit;
from functools import wraps
class logit(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, func):
@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(),而不是@logit
@logit()
def myfunc1():
pass
logit的子類,通過創建子類的方式,來實現更多的功能;
class email_logit(logit):
'''
一個logit的實現版本,可以在函數調用時發送email給管理員
'''
def __init__(self, email='[email protected]', *args, **kwargs):
self.email = email
super(email_logit, self).__init__(*args, **kwargs)
def notify(self):
# 發送一封email到self.email
# 這裏就不做實現了
pass
這樣的話,@email_logit() 將會和 @logit() 產生同樣的效果,但是在打日誌的基礎上,還會多發送一封郵件給管理員