• python 装饰器(八):装饰器实例(五)函数装饰器装饰类以及类方法


    函数装饰器装饰类

    单例模式

    from functools import wraps
    
    def singleton(cls):
        instances = {}
    
        @wraps(cls)
        def get_instance(*args, **kw):
            if cls not in instances:
                instances[cls] = cls(*args, **kw)
            return instances[cls]
        return get_instance

    函数装饰器装饰类方法

    添加异常处理

    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.

     带参数

    def catch_exception(level):
        def decorator(origin_func):
            def wrapper(self, *args, **kwargs):
                print(level)
                try:
                    u = origin_func(self, *args, **kwargs)
                    return u
                except Exception:
                    self.revive() #不用顾虑,直接调用原来的类的方法
                    return 'an Exception raised.'
            return wrapper
        return decorator
    
    
    class Test(object):
        def __init__(self):
            pass
        def revive(self):
            print('revive from exception.')
            # do something to restore
        @catch_exception(level='error')
        def read_value(self):
            print('here I will do something.')
            # do something.
            # 
    
    if __name__ == '__main__':
        t = Test()
        t.read_value()
  • 相关阅读:
    BZOJ 2434: [Noi2011]阿狸的打字机
    BZOJ 3640: JC的小苹果
    BZOJ 1444: [Jsoi2009]有趣的游戏
    BZOJ 4820: [Sdoi2017]硬币游戏
    BZOJ 3670: [Noi2014]动物园
    BZOJ 1009: [HNOI2008]GT考试
    BZOJ 3681: Arietta
    BZOJ 1941: [Sdoi2010]Hide and Seek
    BZOJ 4602: [Sdoi2016]齿轮
    BZOJ 3514: Codechef MARCH14 GERALD07加强版
  • 原文地址:https://www.cnblogs.com/qiu-hua/p/12950280.html
Copyright © 2020-2023  润新知