16
16
17
17
Below provides an example of such Dispatcher, which contains three
18
18
copies of the prototype: 'default', 'objecta' and 'objectb'.
19
-
20
- *TL;DR
21
- Creates new object instances by cloning prototype.
22
19
"""
23
20
21
+ from typing import Any , Dict
24
22
25
- class Prototype :
26
23
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 )
28
28
29
- def clone (self , ** attrs ) :
29
+ def clone (self , ** attrs : Any ) -> None :
30
30
"""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__ )
33
33
obj .__dict__ .update (attrs )
34
34
return obj
35
35
@@ -38,33 +38,36 @@ class PrototypeDispatcher:
38
38
def __init__ (self ):
39
39
self ._objects = {}
40
40
41
- def get_objects (self ):
41
+ def get_objects (self ) -> Dict [ str , Prototype ] :
42
42
"""Get all objects"""
43
43
return self ._objects
44
44
45
- def register_object (self , name , obj ) :
45
+ def register_object (self , name : str , obj : Prototype ) -> None :
46
46
"""Register an object"""
47
47
self ._objects [name ] = obj
48
48
49
- def unregister_object (self , name ) :
49
+ def unregister_object (self , name : str ) -> None :
50
50
"""Unregister an object"""
51
51
del self ._objects [name ]
52
52
53
53
54
- def main ():
54
+ def main () -> None :
55
55
"""
56
56
>>> dispatcher = PrototypeDispatcher()
57
57
>>> prototype = Prototype()
58
58
59
59
>>> d = prototype.clone()
60
60
>>> 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)
62
62
>>> dispatcher.register_object('objecta', a)
63
63
>>> dispatcher.register_object('objectb', b)
64
64
>>> dispatcher.register_object('default', d)
65
65
66
66
>>> [{n: p.value} for n, p in dispatcher.get_objects().items()]
67
67
[{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}]
68
+
69
+ >>> print(b.category, b.is_checked)
70
+ a True
68
71
"""
69
72
70
73
0 commit comments