python 装饰器(七):装饰器实例(四)类装饰器装饰类以及类方法

类装饰器装饰类方法

不带参数

class CatchException:

    def __init__(self,origin_func):
        wraps(origin_func)(self)

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            return types.MethodType(self, instance)


    def __call__(self,*args, **kwargs):

        try:
            return self.__wrapped__(*args, **kwargs)
        except Exception as e:
            print(e)
            return 'an Exception raised.'





class Test(object):
    def __init__(self):
        pass

    def revive(self):
        print('revive from exception.')
        # do something to restore
        
    @CatchException
    def read_value(self):
        print('here I will do something')
        # do something.
        # 

if __name__ == '__main__':
    t = Test()
    t.read_value()

带参数

class CatchException:

    def __init__(self,level):
        self.level = level

    def __call__(self,origin_func):
        def wrapper(origin_func_self,*args, **kwargs):
            print(self.level)
            try:
                u = origin_func(origin_func_self,*args, **kwargs)
                return u
            except Exception as e:
                origin_func_self.revive() #不用顾虑,直接调用原来的类的方法
                print(e)
                return 'an Exception raised.'
        return wrapper



class Test(object):
    def __init__(self):
        pass
    def revive(self):
        print('revive from exception.')
        # do something to restore
    @CatchException(level='error')
    def read_value(self):
        print('here I will do something.')
        # do something.
        # 

if __name__ == '__main__':
    t = Test()
    t.read_value()

猜你喜欢

转载自www.cnblogs.com/qiu-hua/p/12950274.html