一、修饰类方法
def load_detail(func):
def call_func(self, secu):
if not self._detail:
secus = open_securities_detail_pk(secu=secu)
for i in secus:
self._detail[i] = Security(**securities[i])
return func(self)
return call_func
class SecuStore(object):
def __init__(self):
self._detail = {}
@load_detail
def get_all_indexs(self):
return self._detail
SecuStore().get_all_indexs(_type)
def catch_exception(origin_func):
def wrapper(self, *args, **kwargs):
try:
u = origin_func(self, *args, **kwargs)
return u
except Exception:
self.revive() #不用顾虑,直接调用原来的类的方法
return 'an Exception raised.'
return wrapper
class Test(object):
def __init__(self):
pass
def revive(self):
print('revive from exception.')
# do something to restore
@catch_exception
def read_value(self):
print('here I will do something.')
二 、修饰类本身
def decorator(aClass):
class newClass:
def __init__(self, age):
self.total_display = 0
self.wrapped = aClass(age)
def display(self):
self.total_display += 1
print("total display", self.total_display)
self.wrapped.display()
return newClass
@decorator
class Bird:
def __init__(self, age):
self.age = age
def display(self):
print("My age is",self.age)
eagleLord = Bird(5)
for i in range(3):
eagleLord.display()