1 # Copyright (C) 2010-2011 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
13 # Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke. If not, see
17 # <http://www.gnu.org/licenses/>.
19 """Define the :class:`Singleton` class.
21 >>> class A (Singleton):
23 ... print 'initializing instance of %s at (%s)' % (
24 ... self.__class__.__name__, id(self))
26 >>> A_instances = [A() for i in range(3)] # doctest: +ELLIPSIS
27 initializing instance of A at (...)
28 >>> for i in A_instances[1:]:
29 ... print id(i) == id(A_instances[0])
33 Singletons can also be subclassed.
37 >>> B_instances = [B() for i in range(3)] # doctest: +ELLIPSIS
38 initializing instance of B at (...)
39 >>> for i in B_instances[1:]:
40 ... print id(i) == id(B_instances[0])
43 >>> id(A_instances[0]) == id(B_instances[0])
47 class Singleton (object):
50 To create a singleton class, you subclass from Singleton; each
51 subclass will have a single instance, no matter how many times its
52 constructor is called. To further initialize the subclass
53 instance, subclasses should override 'init' instead of __init__ -
54 the __init__ method is called each time the constructor is called.
58 Original implementation from Guido van Rossum's
59 `Unifying types and classes in Python 2.2`_.
61 .. Unifying types and classes in Python 2.2:
62 http://www.python.org/download/releases/2.2.3/descrintro/#__new__
64 def __new__(cls, *args, **kwds):
65 it = cls.__dict__.get('__it__')
68 cls.__it__ = it = object.__new__(cls)
69 it.init(*args, **kwds)
72 def init(self, *args, **kwds):