Skip to content

Commit a12ad8e

Browse files
committed
Update prototype
1 parent 28e8b5f commit a12ad8e

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

patterns/creational/prototype.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,20 @@
1616
1717
Below provides an example of such Dispatcher, which contains three
1818
copies of the prototype: 'default', 'objecta' and 'objectb'.
19-
20-
*TL;DR
21-
Creates new object instances by cloning prototype.
2219
"""
2320

21+
from typing import Any, Dict
2422

25-
class Prototype:
2623

27-
value = "default"
24+
class Prototype:
25+
def __init__(self, value: str = "default", **attrs: Any) -> None:
26+
self.value = value
27+
self.__dict__.update(attrs)
2828

29-
def clone(self, **attrs):
29+
def clone(self, **attrs: Any) -> None:
3030
"""Clone a prototype and update inner attributes dictionary"""
31-
# Python in Practice, Mark Summerfield
32-
obj = self.__class__()
31+
# copy.deepcopy can be used instead of next line.
32+
obj = self.__class__(**self.__dict__)
3333
obj.__dict__.update(attrs)
3434
return obj
3535

@@ -38,33 +38,36 @@ class PrototypeDispatcher:
3838
def __init__(self):
3939
self._objects = {}
4040

41-
def get_objects(self):
41+
def get_objects(self) -> Dict[str, Prototype]:
4242
"""Get all objects"""
4343
return self._objects
4444

45-
def register_object(self, name, obj):
45+
def register_object(self, name: str, obj: Prototype) -> None:
4646
"""Register an object"""
4747
self._objects[name] = obj
4848

49-
def unregister_object(self, name):
49+
def unregister_object(self, name: str) -> None:
5050
"""Unregister an object"""
5151
del self._objects[name]
5252

5353

54-
def main():
54+
def main() -> None:
5555
"""
5656
>>> dispatcher = PrototypeDispatcher()
5757
>>> prototype = Prototype()
5858
5959
>>> d = prototype.clone()
6060
>>> a = prototype.clone(value='a-value', category='a')
61-
>>> b = prototype.clone(value='b-value', is_checked=True)
61+
>>> b = a.clone(value='b-value', is_checked=True)
6262
>>> dispatcher.register_object('objecta', a)
6363
>>> dispatcher.register_object('objectb', b)
6464
>>> dispatcher.register_object('default', d)
6565
6666
>>> [{n: p.value} for n, p in dispatcher.get_objects().items()]
6767
[{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}]
68+
69+
>>> print(b.category, b.is_checked)
70+
a True
6871
"""
6972

7073

0 commit comments

Comments
 (0)