forked from CodeMouse92/DeadSimplePython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhouse_showing.py
More file actions
61 lines (48 loc) · 1.69 KB
/
house_showing.py
File metadata and controls
61 lines (48 loc) · 1.69 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
53
54
55
56
57
58
59
60
61
class House:
def __init__(self, address, house_key, **rooms):
self.address = address
self.__house_key = house_key
self.__locked = True
self._rooms = dict()
for room, desc in rooms.items():
self._rooms[room.replace("_", " ").lower()] = desc
def unlock_house(self, house_key):
if self.__house_key == house_key:
self.__locked = False
print("House unlocked.")
else:
raise RuntimeError("Wrong key! Could not unlock house.")
def explore(self, room):
if self.__locked:
raise RuntimeError("Cannot explore a locked house.")
try:
return f"The {room.lower()} is {self._rooms[room.lower()]}."
except KeyError as e:
raise KeyError(f"No room {room}") from e
def lock_house(self):
self.__locked = True
print("House locked!")
class HouseShowing:
def __init__(self, house, house_key):
self.house = house
self.house_key = house_key
def __enter__(self):
self.house.unlock_house(self.house_key)
return self
def show(self, room):
print(self.house.explore(room))
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
print("Sorry about that.")
self.house.lock_house()
house = House("123 Anywhere Street", house_key=1803,
living_room="spacious",
office="bright",
bedroom="cozy",
bathroom="small",
kitchen="modern")
with HouseShowing(house, house_key=1803) as showing:
showing.show("Living Room")
showing.show("bedroom")
# showing.show("porch")
showing.show("kitchen")