class Singleton(object):
_instance = None
def __new__(self):
if self._instance is None:
self._instance = super(Singleton, self).__new__(self)
return self._instance
if __name__ == '__main__':
a=Singleton()
b=Singleton()
print id(a),id(b)
148991052 148991052
class Singleton(object):
_instance = {}
def __new__(self, id):
try:
return self._instance[id]
except:
d = super(Singleton, self).__new__(self)
self._instance[id] = d
return d
if __name__ == '__main__':
a=Singleton('aaa')
b=Singleton('bbb')
c=Singleton('aaa')
print id(a),id(b),id(c)
144925580 144925516 144925580
class Singleton(dict):
_singltone = {}
def __init__(self):
self.__dict__ = self._singltone
a = Singleton()
b = Singleton()
a.var = 'hello'
print b.var # Выдаст 'hello'