Inheritance should only be used if something is actually the same kind of object conceptually as something else. A booking is not a room, so inheritance makes no sense here. I also don't know what the deal is with Room.rooms
, whether this is some kind of funky static variable or a misused instance variable - in any case, for code like this, Room
should have to keep track of rooms - this should be done by another class (Hotel, maybe). A better model of rooms and bookings etc might look something like this:
class Hotel:
def __init__(self):
self.rooms = {}
def add_room(self, room):
self.rooms[room.number] = room
@classmethod
def from_rooms(cls, rooms):
self = Hotel()
for r in rooms:
self.add_room(r)
return self
def __str__(self):
return "Hotel with rooms:\n{}".format("\n".join(map(str, self.rooms.values())))
class Room:
def __init__(self, number, capacity):
self.number = number
self.capacity = capacity
def __str__(self):
return "Room {} ({} people)".format(self.number, self.capacity)
class RoomFullError(Exception):
pass
class Booking:
def __init__(self, room, guests):
if guests > room.capacity:
raise RoomFullError("This room can only have {} guests, not {}".format(room.capacity, guests))
else:
self.room = room
self.guests = guests
def __str__(self):
return "Booking for {} guests at room ({})".format(self.guests, self.room)
h = Hotel.from_rooms([Room("001", 3), Room("123", 10)])
h.add_room(Room("666", 1))
print(h)
print(h.rooms["001"])
b = Booking(h.rooms["001"], 2)
print(b)
Booking(h.rooms["123"], 500)
This will output:
Hotel with rooms:
Room 001 (3 people)
Room 123 (10 people)
Room 666 (1 people)
Room 001 (3 people)
Booking for 2 guests at room (Room 001 (3 people))
Traceback (most recent call last):
File "code.py", line 46, in <module>
Booking(h.rooms["123"], 500)
File "code.py", line 32, in __init__
raise RoomFullError("This room can only have {} guests, not {}".format(room.capacity, guests))
__main__.RoomFullError: This room can only have 10 guests, not 500
NB the Booking still has access to a Room without inheriting from it, just because it is passed a Room in its __init__
.
This is just a rough outline of what you might do, as I don't know the full details of your project. You should probably have a method for Hotel
that handles and stores bookings, or something. The important thing to take away is that nothing needs to inherit from anything here, and you should define separate classes that have instances of other classes as properties.