Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
52 lines (39 loc) · 1.44 KB
/
Copy pathcode.py
File metadata and controls
52 lines (39 loc) · 1.44 KB
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
class Book:
def __init__(self, name: str, page_count: int):
self.name = name
self.page_count = page_count
self.pages_read = 0
def __repr__(self):
return (
f"<Book {self.name}, read {self.pages_read} pages out of {self.page_count}>"
)
def read(self, pages: int):
self.pages_read += pages
print(f"You have now read {self.pages_read} pages out of {self.page_count}")
python101 = Book("Python 101", 50)
python101.read(35)
python101.read(50) # Whaaaat
# -- Errors used to prevent things from happening --
class TooManyPagesReadError(ValueError):
pass
class Book:
def __init__(self, name: str, page_count: int):
self.name = name
self.page_count = page_count
self.pages_read = 0
def __repr__(self):
return (
f"<Book {self.name}, read {self.pages_read} pages out of {self.page_count}>"
)
def read(self, pages: int):
if self.pages_read + pages > self.page_count:
raise TooManyPagesReadError(
f"You tried to read {self.pages_read + pages} pages, but this book only has {self.page_count} pages."
)
self.pages_read += pages
print(f"You have now read {self.pages_read} pages out of {self.page_count}")
python101 = Book("Python 101", 50)
python101.read(35)
python101.read(
50
) # This now raises an error, which has a helpful name and a helpful error message.