Python编写只允许实例化一个对象的类

2017-05-20 董付国 Python小屋 Python小屋

>>> class T:
    __total = 0
    def __init__(self, value):
        if T.__total != 0:
            raise Exception('You can only create one instanse')
        self.value = value
        T.__total += 1

   
>>> t1 = T(3)

# 实例化第二个对象时出错
>>> t2 = T(5)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    t2 = T(5)
  File "<pyshell#6>", line 5, in __init__
    raise Exception('You can only create one instanse')
Exception: You can only create one instanse


但是,由于Python对私有数据成员没有提供严格的访问控制保护机制,所以上面的代码无法避免下面的情况。

>>> T._T__total = 0
>>> t2 = T(5)
>>> T._T__total = 0
>>> t3 = T(8)
>>> t1
<__main__.T object at 0x0000018771177FD0>
>>> t2
<__main__.T object at 0x0000018771177F98>
>>> t3
<__main__.T object at 0x00000187711F8F98>