1.用 __new__
方法
class Singleton(object): def __new__(cls): if not hasattr(cls,'_instance'): cls._instance=super(Singleton,cls).__new__(cls)# cls.__instance = object.__new__(cls) #这样也可以 return cls._instancea = Singleton()b = Singleton()c = Singleton()print(a,id(a))print(b,id(b))print(c,id(c))
输出:
42443328 42443328 42443328
2.共享属性方法
共享属性:创建实例时把所有实例的__dict__
指向同一个字典,这样它们具有相同的属性和方法.
class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return obclass MyClass2(Borg): a = 1b1 = MyClass2()b2 = MyClass2()b3 = MyClass2()b1.a='萨菲的'b2.a='萨菲02'b1.a='萨菲03'MyClass2.a = 333print(id(b1),id(b2),id(b3))print(b1.a,b3.a,b2.a)print(id(b1.a),id(b2.a),id(b3.a))
输出:
42902024 42902080 42901688萨菲03 萨菲03 萨菲03167568080 167568080 167568080
装饰器版本
def singleton(cls, *args, **kw): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance@singletonclass MyClass: a = 1b1 = MyClass()b2 = MyClass()b3 = MyClass()print(id(b1),id(b2),id(b3))print(b1.a,b3.a,b2.a)
输出:
42712928 42712928 427129281 1 1
类方法版
class Foo(): __v = None @classmethod def get_instance(cls): if cls.__v: print("true: 这是cls.__v",cls.__v) return cls.__v else: print("false: 这是cls.__v", cls.__v) cls.__v = Foo() print("false_1: 这是cls.__v", cls.__v) return cls.__vobj = Foo.get_instance()obj1 = Foo.get_instance()obj2 = Foo.get_instance()obj3 = Foo.get_instance()print(obj,'哈哈',id(obj))print(obj1,'哈哈',id(obj1))print(obj2,'哈哈',id(obj2))print(obj3,'哈哈',id(obj3))
输出:
false: 这是cls.__v Nonefalse_1: 这是cls.__v true: 这是cls.__v true: 这是cls.__v true: 这是cls.__v 哈哈 38798056 哈哈 38798056 哈哈 38798056 哈哈 38798056
单例默认:
'''学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!'''class Singleton(object): def __new__(cls,*args,**kwargs): if not hasattr(cls,'_instance'): print('你好啊',) cls._instance = super(Singleton,cls).__new__(cls) print(cls._instance, '阿斯蒂芬01') return cls._instance print( '阿斯蒂芬') print(cls._instance, '阿斯蒂芬02') return cls._instance a = Singleton()print('这是a',id(a),a)b = Singleton()print('这是b',id(b),b)
输出:
你好啊 阿斯蒂芬01这是a 42516208 阿斯蒂芬 阿斯蒂芬02这是b 42516208