类装饰器使用

参考:http://docs.pythontab.com/

from functools import wraps

class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile

    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打开logfile并写入
            with open(self.logfile, 'a') as opened_file:
                # 现在将日志打到指定的文件
                opened_file.write(log_string + '
')
            # 现在,发送一个通知
            self.notify()
            return func(*args, **kwargs)
        return wrapped_function

    def notify(self):
        # logit只打日志,不做别的
        pass



class email_logit(logit):
    '''
    一个logit的实现版本,可以在函数调用时发送email给管理员
    '''
    def __init__(self, email='admin@myproject.com', *args, **kwargs):
        self.email = email
        super(logit, self).__init__(*args, **kwargs)

    def notify(self):
        # 发送一封email到self.email
        # 这里就不做实现了
        pass

实现该类的单例模式,使用装饰器的方法。装饰器实现单例模式的方法如下


def be_singleten(cls):
    cls._instance = []
    @wraps(cls)
    def wrapped_cls(*args,**kwarsgs):
        if not cls._instance:
            instance = cls(*args,**kwarsgs)
            cls._instance.append(instance)
        else:
            cls._instance[0].__dict__.update(kwarsgs)
        return cls._instance[0]
    return wrapped_cls

@be_singleten
class Test(object):
    """test"""
    def __init__(self,num):
        self.num = num 

if __name__ == '__main__':    
    a = Test(3)
    print a.num
    b = Test(num=4)
    print b.num
    b.num =6
    print a.num
    print id(a),id(b)

#######输出的结果
python2.7
>>>4
>>>6
>>>35090992 35090992

原文地址:https://www.cnblogs.com/by2016/p/6917522.html