-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathborg_one_variable.py
More file actions
66 lines (55 loc) Β· 1.64 KB
/
Copy pathborg_one_variable.py
File metadata and controls
66 lines (55 loc) Β· 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from typing import Dict
class Borg:
_shared_state: Dict[str, str] = {}
def __init__(self):
self.__dict__ = self._shared_state
class YourBorg(Borg):
def __init__(self, state=None):
super().__init__()
if state:
self.state = state
else:
# initiate the first instance with default state
if not hasattr(self, "state"):
self.state = "Init"
def __str__(self):
return self.state
def main():
"""
>>> rm1 = YourBorg()
>>> rm2 = YourBorg()
>>> rm1.state = 'Idle'
>>> rm2.state = 'Running'
>>> print('rm1: {0}'.format(rm1))
rm1: Running
>>> print('rm2: {0}'.format(rm2))
rm2: Running
# When the `state` attribute is modified from instance `rm2`,
# the value of `state` in instance `rm1` also changes
>>> rm2.state = 'Zombie'
>>> print('rm1: {0}'.format(rm1))
rm1: Zombie
>>> print('rm2: {0}'.format(rm2))
rm2: Zombie
# Even though `rm1` and `rm2` share attributes, the instances are not the same
>>> rm1 is rm2
False
# New instances also get the same shared state
>>> rm3 = YourBorg()
>>> print('rm1: {0}'.format(rm1))
rm1: Zombie
>>> print('rm2: {0}'.format(rm2))
rm2: Zombie
>>> print('rm3: {0}'.format(rm3))
rm3: Zombie
# A new instance can explicitly change the state during creation
>>> rm4 = YourBorg('Running')
>>> print('rm4: {0}'.format(rm4))
rm4: Running
# Existing instances reflect that change as well
>>> print('rm3: {0}'.format(rm3))
rm3: Running
"""
if __name__ == "__main__":
import doctest
doctest.testmod()