This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathprototype.py
76 lines (60 loc) · 1.87 KB
/
prototype.py
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
67
68
69
70
71
72
73
74
75
76
"""Prototype pattern
"""
import copy
from collections import OrderedDict
class Book:
def __init__(self, name, authors, price, **kwargs):
"""Examples of kwargs: publisher, length, tags, publication date"""
self.name = name
self.authors = authors
self.price = price
self.__dict__.update(kwargs)
def __str__(self):
mylist = []
ordered = OrderedDict(sorted(self.__dict__.items()))
for i in ordered.keys():
mylist.append("{}: {}".format(i, ordered[i]))
if i == "price":
mylist.append("$")
mylist.append("\n")
return "".join(mylist)
class Prototype:
def __init__(self):
self.objects = dict()
def register(self, identifier, obj):
self.objects[identifier] = obj
def unregister(self, identifier):
del self.objects[identifier]
def clone(self, identifier, **attr):
found = self.objects.get(identifier)
if not found:
raise ValueError("Incorrect object identifier: {}".format(identifier))
obj = copy.deepcopy(found)
obj.__dict__.update(attr)
return obj
def main():
b1 = Book(
name="The C Programming Language",
authors=("Brian W. Kernighan", "Dennis M.Ritchie"),
price=118,
publisher="Prentice Hall",
length=228,
publication_date="1978-02-22",
tags=("C", "programming", "algorithms", "data structures"),
)
prototype = Prototype()
cid = "k&r-first"
prototype.register(cid, b1)
b2 = prototype.clone(
cid,
name="The C Programming Language (ANSI)",
price=48.99,
length=274,
publication_date="1988-04-01",
edition=2,
)
for i in (b1, b2):
print(i)
print("ID b1 : {} != ID b2 : {}".format(id(b1), id(b2)))
if __name__ == "__main__":
main()