完整的单例模式

基于 __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)

应用场景:

  • django中settings配置文件
  • django的admin内部使用,将所有model类注册到了一个字典中。

new`方法返回的是什么?

新创建的对象,内部没有数据,需要经过init来进行初始化。
原文地址:https://www.cnblogs.com/lvweihe/p/12637760.html