File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -4,3 +4,5 @@ __pycache__
44* .egg-info /
55.tox /
66venv
7+ .vscode /
8+ .python-version
Original file line number Diff line number Diff line change 2525https://github.com/onetwopunch/pythonDbTemplate/blob/master/database.py
2626
2727*References:
28- https://fkromer.github.io/python-pattern-references/design/#singleton
28+ - https://fkromer.github.io/python-pattern-references/design/#singleton
29+ - https://learning.oreilly.com/library/view/python-cookbook/0596001673/ch05s23.html
30+ - http://www.aleax.it/5ep.html
2931
3032*TL;DR
3133Provides singleton-like behavior sharing state between instances.
3234"""
3335
3436
3537class Borg :
36- __shared_state = {}
38+ _shared_state = {}
3739
3840 def __init__ (self ):
39- self .__dict__ = self .__shared_state
40- self .state = 'Init'
41-
42- def __str__ (self ):
43- return self .state
41+ self .__dict__ = self ._shared_state
4442
4543
4644class YourBorg (Borg ):
47- pass
4845
46+ def __init__ (self , state = None ):
47+ super ().__init__ ()
48+ if state :
49+ self .state = state
50+ else :
51+ # initiate the first instance with default state
52+ if not hasattr (self , 'state' ):
53+ self .state = 'Init'
54+
55+ def __str__ (self ):
56+ return self .state
57+
4958
5059def main ():
5160 """
52- >>> rm1 = Borg ()
53- >>> rm2 = Borg ()
61+ >>> rm1 = YourBorg ()
62+ >>> rm2 = YourBorg ()
5463
5564 >>> rm1.state = 'Idle'
5665 >>> rm2.state = 'Running'
@@ -73,15 +82,25 @@ def main():
7382 >>> rm1 is rm2
7483 False
7584
76- # Shared state is also modified from a subclass instance `rm3`
85+ # New instances also get the same shared state
7786 >>> rm3 = YourBorg()
7887
7988 >>> print('rm1: {0}'.format(rm1))
80- rm1: Init
89+ rm1: Zombie
8190 >>> print('rm2: {0}'.format(rm2))
82- rm2: Init
91+ rm2: Zombie
92+ >>> print('rm3: {0}'.format(rm3))
93+ rm3: Zombie
94+
95+ # A new instance can explicitly change the state during creation
96+ >>> rm4 = YourBorg('Running')
97+
98+ >>> print('rm4: {0}'.format(rm4))
99+ rm4: Running
100+
101+ # Existing instances reflect that change as well
83102 >>> print('rm3: {0}'.format(rm3))
84- rm3: Init
103+ rm3: Running
85104 """
86105
87106
You can’t perform that action at this time.
0 commit comments