class T(object):
def __init__(self,a):
self.a=a
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls)
return cls._instance
a=T(1)
b=T(2)
print(id(a),id(b),b.a,a.a)
(1887782887832, 1887782887832, 2, 2)
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super().__new__(cls)
return cls._instance
class T2(Singleton):
def __init__(self,a):
self.a=a
c=T2(1)
d=T2(2)
(id(c),id(d),c.a,d.a)
(1887782890352, 1887782890352, 2, 2)
class T3(Singleton):
def __init__(self,a):
self.a=a
e=T3(1)
f=T3(9)
print(id(e),id(f),c.a,d.a,e.a,f.a)
(1887782890520, 1887782890520, 2, 2, 9, 9)