Python中定义只能实例化一个对象的类

2016-09-16 董付国 Python小屋 Python小屋

>>> class Single(object):

total = 0

def __init__(self):

if Single.total > 0:

raise Exception('You can create only one instance.')

Single.total += 1


>>> a = Single()

>>> b = Single()

Traceback (most recent call last):

  File "<pyshell#40>", line 1, in <module>

    b = Single()

  File "<pyshell#38>", line 5, in __init__

    raise Exception('You can create only one instance.')

Exception: You can create only one instance.