單例模式
單例模式:每次例項化物件都是用的同一個記憶體地址【第一個物件】。
-
基於模組匯入實現
-
基於物件導向實現
手撕一個單例模式示例:
import threading class Singleton: instance = None lock = threading.RLock() def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): if cls.instance: return cls.instance with cls.lock: if cls.instance: return cls.instance import time cls.instance = object.__new__(cls) return cls.instance def task(): obj = Singleton("x") print(obj) for i in range(10): t = threading.Thread(target=task) t.start()