Programs & Examples
OOP in Python · Study material
A small library system
Two cooperating classes: Book stores its state and describes itself with __repr__; Library keeps books in a dict and applies the borrowing rules.
class Book:
def __init__(self, title, author):
self.title, self.author = title, author
self.borrowed_by = None
def __repr__(self):
status = f"borrowed by {self.borrowed_by}" if self.borrowed_by else "available"
return f"{self.title} ({status})"
class Library:
def __init__(self):
self.books = {}
def add(self, book):
self.books[book.title] = book
def borrow(self, title, member):
book = self.books.get(title)
if book is None:
return f"{title}: not in the library"
if book.borrowed_by:
return f"{title}: already borrowed"
book.borrowed_by = member
return f"{title}: issued to {member}"
lib = Library()
lib.add(Book("Python 101", "Rao"))
lib.add(Book("SQL Basics", "Iyer"))
for title, member in [("Python 101", "Asha"), ("Python 101", "Ravi"), ("Java", "Dev")]:
print(lib.borrow(title, member))
print(list(lib.books.values()))
Python 101: issued to Asha Python 101: already borrowed Java: not in the library [Python 101 (borrowed by Asha), SQL Basics (available)]
Properties with validation
The encapsulation example on the Introduction tab protects a balance with a property setter and shows name mangling of a __pin attribute.