# 单例模式 # 写法一 # class Singleton: # def __new__(cls, *args, **kwargs): # if not hasattr(cls,"_instance"): # cls._instance = super(Singleton,cls).__new__(cls) # return cls._instance # # class MyClass(Singleton): # def __init__(self,a): # print("init ~~`") # self.a = a # # 写法二 class Singleton_02: __obj = None __initFlag__ = True a = 0 def __new__(cls, *args, **kwargs): if cls.__obj == None: cls.__obj = object.__new__(cls) return cls.__obj def __init__(self, a): self.a = a if Singleton_02.__initFlag__: print(‘init~~~‘) Singleton_02.__initFlag__ = False def GetNumber(self): print(self.a) a1 = Singleton_02(11) a1.GetNumber() b = Singleton_02(22) b.GetNumber() print(id(a1), id(b))
原文:https://www.cnblogs.com/Anec/p/14054991.html