方法一:利用装饰器
定义一个类变量,同时也定义一个类方法class classthond:
driver=None
def __init__(self):
pass
@classmethod
def get_driver(cls):
if cls.driver==None:
cls.driver="T"
return cls.driver
k=classthond() #实例2个对象
k2=classthond() #实例2个对象
k.get_driver()
print("实例2个对象如下:")
print(id(k))
print(id(k2))
print("所有的实例的类变量都是引用同一个")
print(id(k.driver))
print(id(k2.driver))
结果:
实例2个对象如下:
1747171957872
1747172109328
所有的实例的类变量都是引用同一个:
1747171989680
1747171989680
方法二:用__new__()方法
class singe: instant=None #设置一个空对象 flag=False #定义对象是否被初始化 def __new__(cls): if cls.instant==None: cls.instant = super().__new__(cls) return cls.instance def __init__(self): if singe.flag: return self.newDate="初始数据" singe.flag=True
方法三:模块
定义好一个类,并在模块中实例一个对象。导入模块时,就是实例一个对象(因为模块导入的时候只执行一次)
class singe: def __init__(self): """这里可以写一个需要初始化的""" self.name="测试单例模式" pass def get_att(self): return self.name test_singe=singe() #这些代码保存在一个singe.py中,然后导入 from singe import test_singe