I've been reading Thinking in python by Bruce Eckel. Currently, I'm reading the Pattern Concept chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inheritance, instead of privated nested class).
This is my understanding of the code so far:
- All Singleton objects are subclasses of Borg
- _shared_state is initially an empty dictionary
- _shared_state is a global variable; Any objects utilizing Borg will have the same _shared_state value
My confusion so far:
- What's the purpose of this line:
self.__dict__ = self._shared_state
; or the purpose of the dictionary - How did all the objects of Singletons eventually have the same val, even though they are all different instances of the class.
- In overall, I don't know how Borg works
Many Many thanks in advance!
-Tri
*Update: What is stored in _shared_state after each Singleton object creation?
#: Alex' Martelli's Singleton in Python
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
x = Singleton('sausage')
print x
y = Singleton('eggs')
print y
z = Singleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__.Singleton instance at 0079EF2C>
<__main__.Singleton instance at 0079E10C>
<__main__.Singleton instance at 00798F9C>
'''