最简单最常用的实现方法:
class SingletonObject(object):
def __new__(cls):
if not hasattr(SingletonObject, '_single'):
SingletonObject._single = object.__new__(cls)
return SingletonObject._single
def __init__(self):
self.val = None
def __str__(self):
return "{0!r}, {1}".format(self, self.val)
a = SingletonObject()
a.val = 123
print(a)
b = SingletonObject()
b.val = 1234
print(a)
print(b)
"""
-------以下为打印信息----------
<__main__.SingletonObject object at 0x10ef76130>, 123
<__main__.SingletonObject object at 0x10ef76130>, 1234
<__main__.SingletonObject object at 0x10ef76130>, 1234
----------------------------"""
# 可以看到SingletonObject的实例a和b指向同一个内存地址0x10ef76130