I'm trying to be more deep in OOP and SOLID in python and here's a scenario I tried to learn more about it.
Design a small OOP system for a library with these rules:
There are different types of items in the library:
Book (with author, title, pages)
Magazine (with title, issue number)
DVD (with title, duration in minutes)
Each type of item calculates borrow fee differently:
Book → 1 per 100 pages.
Magazine → fixed 2.
DVD → 0.05 per minute of duration.
Here's my implementation:
from abc import ABC, abstractmethod
class LibraryItem(ABC):
def __init__(self, title: str):
super().__init__()
self.title = title
@abstractmethod
def borrow(self):
pass
class Book(LibraryItem):
def __init__(self, title: str, author: str, pages: int):
super().__init__(title)
self.author = author
self.pages = pages
def borrow(self):
return 1 * (self.pages / 100)
class Magazine(LibraryItem):
def __init__(self, title: str, issue_number: int):
super().__init__(title)
self.issue_number = issue_number
def borrow(self):
return 2
class DVD(LibraryItem):
def __init__(self, title: str, duration: int):
super().__init__(title)
self.duration = duration
def borrow(self):
return self.duration * 0.05
class Library:
def __init__(self):
self.tracked = []
def borrow_request(self, library_item: LibraryItem):
self.tracked.append(library_item)
def total_fee(self):
total_fee = 0.0
for item in self.tracked:
total_fee += item.borrow()
return {"borrowed_items": [track_item.title for track_item in self.tracked], "total_fee": total_fee}
I used abstract method for this design because we need borrow function for all child of Library items with different logic.
My sample code support also polymorphism and this code extendable if we want to add new category for library items.
This design leverages abstract base classes to enforce the borrow method across all item types while allowing each subclass to define its own fee calculation logic, promoting the Open-Closed Principle from SOLID.
If you have any questions, suggestions, or ideas for improving this implementation (or extending it further), I'd love to hear them—feel free to drop a comment below!
Top comments (0)