|
| 1 | +class House: |
| 2 | + def __init__(self, address, house_key, **rooms): |
| 3 | + self.address = address |
| 4 | + self.__house_key = house_key |
| 5 | + self.__locked = True |
| 6 | + self._rooms = dict() |
| 7 | + for room, desc in rooms.items(): |
| 8 | + self._rooms[room.replace("_", " ").lower()] = desc |
| 9 | + |
| 10 | + def unlock_house(self, house_key): |
| 11 | + if self.__house_key == house_key: |
| 12 | + self.__locked = False |
| 13 | + print("House unlocked.") |
| 14 | + else: |
| 15 | + raise RuntimeError("Wrong key! Could not unlock house.") |
| 16 | + |
| 17 | + def explore(self, room): |
| 18 | + if self.__locked: |
| 19 | + raise RuntimeError("Cannot explore a locked house.") |
| 20 | + |
| 21 | + try: |
| 22 | + return f"The {room.lower()} is {self._rooms[room.lower()]}." |
| 23 | + except KeyError as e: |
| 24 | + raise KeyError(f"No room {room}") from e |
| 25 | + |
| 26 | + def lock_house(self): |
| 27 | + self.__locked = True |
| 28 | + print("House locked!") |
| 29 | + |
| 30 | + |
| 31 | +class HouseShowing: |
| 32 | + |
| 33 | + def __init__(self, house, house_key): |
| 34 | + self.house = house |
| 35 | + self.house_key = house_key |
| 36 | + |
| 37 | + def __enter__(self): |
| 38 | + self.house.unlock_house(self.house_key) |
| 39 | + return self |
| 40 | + |
| 41 | + def show(self, room): |
| 42 | + print(self.house.explore(room)) |
| 43 | + |
| 44 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 45 | + if exc_type: |
| 46 | + print("Sorry about that.") |
| 47 | + self.house.lock_house() |
| 48 | + |
| 49 | + |
| 50 | +house = House("123 Anywhere Street", house_key=1803, |
| 51 | + living_room="spacious", |
| 52 | + office="bright", |
| 53 | + bedroom="cozy", |
| 54 | + bathroom="small", |
| 55 | + kitchen="modern") |
| 56 | + |
| 57 | +with HouseShowing(house, house_key=1803) as showing: |
| 58 | + showing.show("Living Room") |
| 59 | + showing.show("bedroom") |
| 60 | + # showing.show("porch") |
| 61 | + showing.show("kitchen") |
0 commit comments