單例模式:一個類不管實例化多少次,返回的都是同一個實例,例如:a1=A(), a2=A(), a3=A(),a一、a2和a3其實都是同一個對象,即print(a1 is a2)和print(a2 is a3)都會打印True。html
實現方式:有兩種方式,一種是使用元類metaclass控制類實例化時的對象,另外一種是使用類的__new__方法控制類返回的對象,推薦使用元類的方式,由於__new__一般是用來改變類結構的。eclipse
注:關於元類和單例模式,本文只是貼了兩個簡單的示例代碼和本身的一些心得,想要更加深刻的學習,這裏有一篇博客講得很詳細https://www.cnblogs.com/tkqasn/p/6524879.html學習
元類實現單例模式(Python3.6):spa
1 class Singleton(type): 2 def __init__(cls, *args, **kwargs): 3 cls.__instance = None 4 super().__init__(*args, **kwargs) 5 6 def __call__(cls, *args, **kwargs): 7 if cls.__instance is None: 8 cls.__instance = super().__call__(*args, **kwargs) 9 10 return cls.__instance 11 12 13 class MySingleton(metaclass=Singleton): 14 def __init__(self, val): 15 self.val = val 16 print(self.val) 17 18 19 hello = MySingleton('hello') 20 hi = MySingleton('hi') 21 print(hello is hi) 22 23 ----------輸出結果---------- 24 hello 25 True
>>> int.__class__ <class 'type'> >>> num = 3 >>> num.__class__ <class 'int'> >>> num.__class__.__class__ <class 'type'> >>> >>> >>> class A: pass >>> A.__class__ <class 'type'> >>> a = A() >>> a.__class__ <class '__main__.A'> >>> a.__class__.__class__ <class 'type'> >>>
__new__實現單例模式(Python3.6):code
1 class MySingleton: 2 def __init__(self, val): 3 self.val = val
4 print(self.val)
5 print(self.__dict__) 6 7 def __new__(cls, *args, **kwargs): 8 if not hasattr(cls, '_instance'): 9 cls._instance = super().__new__(cls) 10 11 return cls._instance 12 13 14 hello = MySingleton('hello') 15 hi = MySingleton('hi') 16 print(hello is hi) 17 18 19 -----------輸出結果-------------- 20 hello
21 {'val': 'hello'}
22 hi
23 {'val': 'hi'}
24 True