Classes and Objects: Exercise Answers#
Book class — properties with
__prefix,@property/setter decorators, comparison dunder methods,__str__,__repr__, and anavg_unit_pricecomputed property.
1class Book:
2 def __init__(self, name, authors, publisher, list_price, num_units_sold, total_sales):
3 self.__name = name
4 self.__authors = authors
5 self.__publisher = publisher
6 self.__list_price = list_price
7 self.__num_units_sold = num_units_sold
8 self.__total_sales = total_sales
9
10 # --- read-only properties ---
11 @property
12 def name(self):
13 return self.__name
14
15 @property
16 def authors(self):
17 return self.__authors
18
19 @property
20 def publisher(self):
21 return self.__publisher
22
23 # --- read/write properties ---
24 @property
25 def list_price(self):
26 return self.__list_price
27
28 @list_price.setter
29 def list_price(self, value):
30 self.__list_price = value
31
32 @property
33 def num_units_sold(self):
34 return self.__num_units_sold
35
36 @num_units_sold.setter
37 def num_units_sold(self, value):
38 self.__num_units_sold = value
39
40 @property
41 def total_sales(self):
42 return self.__total_sales
43
44 @total_sales.setter
45 def total_sales(self, value):
46 self.__total_sales = value
47
48 # --- computed property ---
49 @property
50 def avg_unit_price(self):
51 if self.__num_units_sold == 0:
52 return 0.0
53 return self.__total_sales / self.__num_units_sold
54
55 # --- comparison (by name) ---
56 def __eq__(self, other): return self.__name == other.__name
57 def __lt__(self, other): return self.__name < other.__name
58 def __le__(self, other): return self.__name <= other.__name
59 def __gt__(self, other): return self.__name > other.__name
60 def __ge__(self, other): return self.__name >= other.__name
61
62 # --- string representations ---
63 def __str__(self):
64 authors_str = ', '.join(self.__authors)
65 return f'{authors_str}. "{self.__name}". {self.__publisher}. ${self.__list_price:.2f}'
66
67 def __repr__(self):
68 return (
69 f"{{\"name\": {self.__name!r}, \"authors\": {self.__authors!r}, "
70 f"\"publisher\": {self.__publisher!r}, \"list_price\": {self.__list_price}, "
71 f"\"num_units_sold\": {self.__num_units_sold}, "
72 f"\"total_sales\": {self.__total_sales}}}"
73 )
1fowler_book = Book(
2 'Refactoring: Improving the Design of Existing Code',
3 ['Martin Fowler'], 'Addison Wesley', 39.95, 4_023_342, 120_000_000.00)
4
5gof_book = Book(
6 'Design Patterns: Elements of Reusable Object-Oriented Software',
7 ['Erich Gamma', 'Richard Helm', 'Ralph Johnson', 'John Vlissides'],
8 'Addison Wesley', 45.95, 5_123_423, 224_234_954.00)
9
10c_book = Book(
11 'The C Programming Language',
12 ['Brian W. Kernighan', 'Dennis M. Ritchie'],
13 'Prentice Hall', 60.30, 9_343_123, 433_231_924.00)
14
15print(fowler_book)
16print(repr(gof_book))
17print(f'avg unit price: ${c_book.avg_unit_price:.2f}')
18print(f'fowler < gof: {fowler_book < gof_book}') # False (R < D)
19print(f'fowler > c: {fowler_book > c_book}') # True (R > T)
Martin Fowler. "Refactoring: Improving the Design of Existing Code". Addison Wesley. $39.95
{"name": 'Design Patterns: Elements of Reusable Object-Oriented Software', "authors": ['Erich Gamma', 'Richard Helm', 'Ralph Johnson', 'John Vlissides'], "publisher": 'Addison Wesley', "list_price": 45.95, "num_units_sold": 5123423, "total_sales": 224234954.0}
avg unit price: $46.37
fowler < gof: False
fowler > c: False
Bookshelf class —
add_book,remove_book_by_title,find_most_expensive_book.
1class Bookshelf:
2 def __init__(self):
3 self.__books = []
4
5 def add_book(self, book):
6 self.__books.append(book)
7
8 def remove_book_by_title(self, title):
9 self.__books = [b for b in self.__books if b.name != title]
10
11 def find_most_expensive_book(self):
12 if not self.__books:
13 return None
14 return max(self.__books, key=lambda b: b.list_price)
1shelf = Bookshelf()
2shelf.add_book(fowler_book)
3shelf.add_book(gof_book)
4shelf.add_book(c_book)
5
6print('Most expensive:', shelf.find_most_expensive_book().name)
7
8shelf.remove_book_by_title('The C Programming Language')
9print('After removal:', shelf.find_most_expensive_book().name)
Most expensive: The C Programming Language
After removal: Design Patterns: Elements of Reusable Object-Oriented Software