首页 > 编程语言 > 详细

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

时间:2020-05-25 15:15:06      阅读:39      评论:0      收藏:0      [点我收藏+]

类装饰器装饰类方法

不带参数

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()

 

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

原文:https://www.cnblogs.com/qiu-hua/p/12950274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!