|
19 | 19 | added to the instance's attribute dictionary, but, since the attribute |
20 | 20 | dictionary itself is shared (which is __shared_state), all other |
21 | 21 | attributes will also be shared. |
22 | | -For this reason, when the attribute self.state is modified using |
23 | | -instance rm2, the value of self.state in instance rm1 also changes. The |
24 | | -same happens if self.state is modified using rm3, which is an |
25 | | -instance from a subclass. |
26 | | -Notice that even though they share attributes, the instances are not |
27 | | -the same, as seen by their ids. |
28 | 22 |
|
29 | 23 | *Where is the pattern used practically? |
30 | 24 | Sharing state is useful in applications like managing database connections: |
@@ -53,37 +47,44 @@ class YourBorg(Borg): |
53 | 47 | pass |
54 | 48 |
|
55 | 49 |
|
56 | | -if __name__ == '__main__': |
57 | | - rm1 = Borg() |
58 | | - rm2 = Borg() |
| 50 | +def main(): |
| 51 | + """ |
| 52 | + >>> rm1 = Borg() |
| 53 | + >>> rm2 = Borg() |
59 | 54 |
|
60 | | - rm1.state = 'Idle' |
61 | | - rm2.state = 'Running' |
| 55 | + >>> rm1.state = 'Idle' |
| 56 | + >>> rm2.state = 'Running' |
62 | 57 |
|
63 | | - print('rm1: {0}'.format(rm1)) |
64 | | - print('rm2: {0}'.format(rm2)) |
| 58 | + >>> print('rm1: {0}'.format(rm1)) |
| 59 | + rm1: Running |
| 60 | + >>> print('rm2: {0}'.format(rm2)) |
| 61 | + rm2: Running |
65 | 62 |
|
66 | | - rm2.state = 'Zombie' |
| 63 | + # When the `state` attribute is modified from instance `rm2`, |
| 64 | + # the value of `state` in instance `rm1` also changes |
| 65 | + >>> rm2.state = 'Zombie' |
67 | 66 |
|
68 | | - print('rm1: {0}'.format(rm1)) |
69 | | - print('rm2: {0}'.format(rm2)) |
| 67 | + >>> print('rm1: {0}'.format(rm1)) |
| 68 | + rm1: Zombie |
| 69 | + >>> print('rm2: {0}'.format(rm2)) |
| 70 | + rm2: Zombie |
70 | 71 |
|
71 | | - print('rm1 id: {0}'.format(id(rm1))) |
72 | | - print('rm2 id: {0}'.format(id(rm2))) |
| 72 | + # Even though `rm1` and `rm2` share attributes, the instances are not the same |
| 73 | + >>> rm1 is rm2 |
| 74 | + False |
73 | 75 |
|
74 | | - rm3 = YourBorg() |
| 76 | + # Shared state is also modified from a subclass instance `rm3` |
| 77 | + >>> rm3 = YourBorg() |
75 | 78 |
|
76 | | - print('rm1: {0}'.format(rm1)) |
77 | | - print('rm2: {0}'.format(rm2)) |
78 | | - print('rm3: {0}'.format(rm3)) |
| 79 | + >>> print('rm1: {0}'.format(rm1)) |
| 80 | + rm1: Init |
| 81 | + >>> print('rm2: {0}'.format(rm2)) |
| 82 | + rm2: Init |
| 83 | + >>> print('rm3: {0}'.format(rm3)) |
| 84 | + rm3: Init |
| 85 | + """ |
79 | 86 |
|
80 | | -### OUTPUT ### |
81 | | -# rm1: Running |
82 | | -# rm2: Running |
83 | | -# rm1: Zombie |
84 | | -# rm2: Zombie |
85 | | -# rm1 id: 140732837899224 |
86 | | -# rm2 id: 140732837899296 |
87 | | -# rm1: Init |
88 | | -# rm2: Init |
89 | | -# rm3: Init |
| 87 | + |
| 88 | +if __name__ == "__main__": |
| 89 | + import doctest |
| 90 | + doctest.testmod() |
0 commit comments