1. 程式人生 > >Python 裝飾器裝飾類中的方法(轉)

Python 裝飾器裝飾類中的方法(轉)

some print raised blog python bject decorate pass div

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.‘)
# do something.

原文地址:https://kingname.info/2017/04/17/decorate-for-method/

Python 裝飾器裝飾類中的方法(轉)