Skip to content
Snippets Groups Projects
Commit 2952ab6d authored by sveseli's avatar sveseli
Browse files

reordered initialization call, added some test code

parent 9c172fe3
No related branches found
No related tags found
No related merge requests found
......@@ -4,12 +4,16 @@ class Singleton(object):
__instance = None
# This class will behave properly as long as getInstance() is called.
# If object is constructed using constructor, __init__() will be called
# multiple times in the derived class (i.e., one needs protection
# against multiple initializations in the derived class)
def __new__(cls, *args, **kwargs):
# Allow subclasses to create their own instances.
if cls.__instance is None or cls != type(cls.__instance):
instance = object.__new__(cls, *args, **kwargs)
cls.__instance = instance
instance.__init__(*args, **kwargs)
cls.__instance = instance
return cls.__instance
@classmethod
......@@ -18,12 +22,13 @@ class Singleton(object):
def __init__(self, *args, **kwargs):
# Only initialize once.
if Singleton.__instance is not None:
if self.__class__.__instance is not None:
return
####################################################################
# Testing
if __name__ == '__main__':
print 'Testing Singleton class'
s1 = Singleton.getInstance()
s2 = Singleton()
s3 = Singleton.getInstance()
......@@ -33,8 +38,11 @@ if __name__ == '__main__':
print 'S3: ', s3
print 'S4: ', s4
class A(Singleton):
__instance = None
def __init__(self, x):
self.x = x
if self.__class__.__instance is None:
print 'in A.__init__()'
self.x = x
class B(Singleton):
def __init__(self, x):
self.x = x
......@@ -42,18 +50,31 @@ if __name__ == '__main__':
def __init__(self):
self.x = 14
print
print 'Testing Class A'
print 'Init A(3)'
a1 = A(3)
print 'Init A(4)'
a2 = A(4)
print 'A.getInstance()'
a3 = A.getInstance()
print 'A.getInstance()'
a4 = A.getInstance()
print a1
print a2
print a2.x, a1.x
print a3
print a3.x, a2.x, a1.x
print
print 'Testing Class B'
b1 = B(6)
b2 = B(5)
print b1
print b2
print b2.x, b1.x
print
print 'Testing Class C'
c1 = C()
c2 = C()
print c1
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment