接上节内容,我们继续介绍类装饰器,顾名思义类装饰器就是类闭包。



定义一个类装饰器Python-19-类装饰器_git



需求:实现一个类装饰器,能够在方法执行时打印日志,并且发送通知到指定地方。

from functools import wraps

class logAndNotify(object):

# 初始化,定义日志路径
def __init__(self,logfile='service.log'):
self.logfile = logfile

# 使类成为可调用对象
def __call__(self,func):

@wraps(func)
def wrap_func(*args,**kwargs):
info = func.__name__+'was called'

# 实现写日志
with open(self.logfile,'a') as f:
f.write(info+'\n')

# 实现通知
self.notify()

return func(*args,**kwargs)
return wrap_func

def notify(self):
print('notify has been send...')

@logAndNotify()
def sayHi(name):
print('hello',name,'!')

res = sayHi('phyger')
print(res)


执行结果:


➜ RemoteWorking git:(master) ✗ /usr/bin/python3 /root/RemoteWorking/test/test.py
notify has been send...
hello phyger !
None



类装饰器功能扩展Python-19-类装饰器_git



如果我们想要在此类装饰器的基础上,增加发送邮件的功能,就可以利用类的继承特性来实现。


from functools import wraps


class logAndNotify(object):

# 初始化,定义日志路径
def __init__(self, logfile="service.log"):
self.logfile = logfile

# 使类成为可调用对象
def __call__(self, func):
@wraps(func)
def wrap_func(*args, **kwargs):
info = func.__name__ + "was called"

# 实现写日志
with open(self.logfile, "a") as f:
f.write(info + "\n")
# 实现通知
self.notify()

return func(*args, **kwargs)

return wrap_func

def notify(self):
print("notify has been send...")


class NewWarp(logAndNotify):

# 初始化邮件地址
def __init__(self, email_address='phyger@', *args, **kwargs):
self.email_address = email_address
super(NewWarp,self).__init__(*args, **kwargs)

# 重写notify方法
def notify(self):
print("notify has been send...")
print('email sended...to',self.email_address)


@NewWarp()
def sayHi(name):
print("hello", name, "!")


res = sayHi("phyger")
print(res)


执行结果:


➜ RemoteWorking git:(master) ✗ /usr/bin/python3 /root/RemoteWorking/test/test.py
notify has been send...
email sended...to phyger@
hello phyger !
None



Python-19-类装饰器_初始化_03