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.

猜你喜欢

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