Exercises: Object-Oriented Programming
Practice classes, inheritance, encapsulation, and magic methods with OOP exercises.
Related chapter: Object-Oriented Programming
Exercise 1: Bank Account
Create a BankAccount class with:
deposit(amount)— add to balancewithdraw(amount)— subtract if sufficient fundsbalanceproperty- Raise
ValueErrorfor invalid amounts or insufficient funds
acc = BankAccount("Alice", 1000)
acc.deposit(500)
acc.withdraw(200)
print(acc.balance) # 1300
Exercise 2: Rectangle and Square
Create a Rectangle class with width, height, area(), and perimeter(). Create a Square class that inherits from Rectangle.
r = Rectangle(4, 5)
print(r.area()) # 20
s = Square(5)
print(s.area()) # 25
Exercise 3: Library System
Design classes for a simple library:
Book(title, author, isbn)Member(name, member_id)Librarythat canadd_book,lend_book,return_book
Track which books are available vs lent out.
Exercise 4: Magic Methods
Create a Vector2D class with:
__init__(x, y)__add__,__sub__,__mul__(scalar)__eq__,__str__,__repr__magnitude()method
v1 = Vector2D(3, 4)
v2 = Vector2D(1, 2)
print(v1 + v2) # (4, 6)
print(v1.magnitude()) # 5.0
Exercise 5: Abstract Shape
Use ABC to create an abstract Shape class with area() and perimeter(). Implement Circle, Rectangle, and Triangle.
Challenge: Card Game
Create a Card and Deck class:
Deckhas 52 cards, canshuffle()anddeal(n)Cardhassuit,rank, and__str__(e.g., “Ace of Spades”)- Write a simple game function that deals two hands and compares sums
Solution (Exercise 1 sketch)
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > self._balance:
raise ValueError("Insufficient funds")
self._balance -= amount
Exercise 6: Property Validation
Create a Person class where age must be between 0 and 150. Use @property and @age.setter to enforce this.
Exercise 7: Composition over Inheritance
Create Engine and Car classes. Car should contain an Engine (composition), not inherit from it. Car.start() delegates to Engine.start().