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

 

posted @ 2020-05-24 11:12  秋华  阅读(461)  评论(0编辑  收藏  举报