__new__
实现单例模式import time
import threading
class Singleton(object):
instance = None
lock = threading.RLock()
def __new__(cls, *arg, **kwargs):
if cls.instance:
return cls.instance
with cls.lock:
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
obj = Singleton()
print(obj)
# sg.py
class Singleton(object):
pass
obj = Singleton()
import sg
print(sg.obj)
新创建的对象,内部没有数据,需要经过init来进行初始化。
原文:https://www.cnblogs.com/lvweihe/p/12637760.html