-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathmain.py
54 lines (45 loc) · 1.88 KB
/
main.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
import json
import xml.etree.ElementTree as ET
class Book:
def __init__(self, title: str, content: str):
self.title = title
self.content = content
def display(self, display_type: str) -> None:
if display_type == "console":
print(self.content)
elif display_type == "reverse":
print(self.content[::-1])
else:
raise ValueError(f"Unknown display type: {display_type}")
def print_book(self, print_type: str) -> None:
if print_type == "console":
print(f"Printing the book: {self.title}...")
print(self.content)
elif print_type == "reverse":
print(f"Printing the book in reverse: {self.title}...")
print(self.content[::-1])
else:
raise ValueError(f"Unknown print type: {print_type}")
def serialize(self, serialize_type: str) -> str:
if serialize_type == "json":
return json.dumps({"title": self.title, "content": self.content})
elif serialize_type == "xml":
root = ET.Element("book")
title = ET.SubElement(root, "title")
title.text = self.title
content = ET.SubElement(root, "content")
content.text = self.content
return ET.tostring(root, encoding="unicode")
else:
raise ValueError(f"Unknown serialize type: {serialize_type}")
def main(book: Book, commands: list[tuple[str, str]]) -> None | str:
for cmd, method_type in commands:
if cmd == "display":
book.display(method_type)
elif cmd == "print":
book.print_book(method_type)
elif cmd == "serialize":
return book.serialize(method_type)
if __name__ == "__main__":
sample_book = Book("Sample Book", "This is some sample content.")
print(main(sample_book, [("display", "reverse"), ("serialize", "xml")]))