The before code repeats name, capacity, and book method in each room type. The after code moves common parts to a base Room class, reducing duplication and making it easier to add new room types.
### Before (No hierarchy, duplicated code)
class ConferenceRoom:
def __init__(self, name, capacity, projector):
self.name = name
self.capacity = capacity
self.projector = projector
def book(self):
print(f"Booking conference room {self.name}")
class Bedroom:
def __init__(self, name, capacity, bed_type):
self.name = name
self.capacity = capacity
self.bed_type = bed_type
def book(self):
print(f"Booking bedroom {self.name}")
### After (Using inheritance)
class Room:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
def book(self):
print(f"Booking room {self.name}")
class ConferenceRoom(Room):
def __init__(self, name, capacity, projector):
super().__init__(name, capacity)
self.projector = projector
class Bedroom(Room):
def __init__(self, name, capacity, bed_type):
super().__init__(name, capacity)
self.bed_type = bed_type
# Usage
conf = ConferenceRoom("Conf A", 50, True)
conf.book() # Booking room Conf A
bed = Bedroom("Bed 1", 2, "King")
bed.book() # Booking room Bed 1