[深入Python]Alex Martelli的Borg类
#!/usr/bin/env python #coding:utf-8 class Borg(object): _share_state = {} def __init__ (self): ''' 将__dict__和_share_state指向了同一个地址 这样会使_share_state的内容始终保持与__dict__同步 由于_share_state是类变量,最终就可以实现多个实例的__dict__保持同步的效果 ''' self.__dict__ = self._share_state class Singleton(Borg): def __init__ (self, *args, **kwargs): super(Singleton, self).__init__() self.val = args[0] def __str__ (self): return self.val x = Singleton('test1') y = Singleton('test2') z = Singleton('test3') print x #test3 print y #test3 print z #test3
本文涉及的知识点:
1、__dict__
2、类变量
3、super
4、__str__
5、Python赋值的原理