最简单最常用的实现方法:

    1. class SingletonObject(object):
    2. def __new__(cls):
    3. if not hasattr(SingletonObject, '_single'):
    4. SingletonObject._single = object.__new__(cls)
    5. return SingletonObject._single
    6. def __init__(self):
    7. self.val = None
    8. def __str__(self):
    9. return "{0!r}, {1}".format(self, self.val)
    10. a = SingletonObject()
    11. a.val = 123
    12. print(a)
    13. b = SingletonObject()
    14. b.val = 1234
    15. print(a)
    16. print(b)
    17. """
    18. -------以下为打印信息----------
    19. <__main__.SingletonObject object at 0x10ef76130>, 123
    20. <__main__.SingletonObject object at 0x10ef76130>, 1234
    21. <__main__.SingletonObject object at 0x10ef76130>, 1234
    22. ----------------------------"""
    23. # 可以看到SingletonObject的实例a和b指向同一个内存地址0x10ef76130