import traceback
def close_connection():
def _wrapper(func):
def __wrapper(self, *args, **kwargs):
try:
result = func(self, *args, **kwargs)
return result
except Exception, e:
print ('Exception: %s' % traceback.format_exc())
raise e
finally:
self.close()
return __wrapper
return _wrapper
class Caculator(object):
@close_connection()
def chufa(self, x, y):
try:
result = x/y
except Exception, e:
raise e
return result
def close(self):
print "CLOSE !!!"
caculator = Caculator()
result = caculator.chufa(6, 0)
print result
[1] PEP 318 - Decorators for Functions and Methods
[2] https://docs.python.org/2/library/functions.html#property