1. 程式人生 > >【python】如何在類方法前新增裝飾器

【python】如何在類方法前新增裝飾器

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