Chapter 7 Exercises
Comprehensive exercises covering object-oriented programming in Python, sorted from easiest to hardest.
Exercises
Exercise 1: Basic Class and Object
Create a class called Student with instance variables name and student_id. Create a constructor that initializes these values. Read name and student_id from input, create a Student object, and print both attributes.
Basic Class and Object
class Student: def __init__(self, name, student_id): self.name = name self.student_id = student_id
name = input()student_id = input()student = Student(name, student_id)print(f"Name: {student.name}, Student ID: {student.student_id}")Exercise 2: Instance Methods
Create a class called Rectangle with instance variables length and width. Add methods area() and perimeter() that return the area and perimeter respectively. Read length and width from input, create a Rectangle, and display both values.
Instance Methods
class Rectangle: def __init__(self, length, width): self.length = length self.width = width
def area(self): return self.length * self.width
def perimeter(self): return 2 * (self.length + self.width)
length = float(input())width = float(input())rect = Rectangle(length, width)print(f"Area: {rect.area()}")print(f"Perimeter: {rect.perimeter()}")Exercise 3: Class Variables and Methods
Create a class called Counter with a class variable count = 0. In the constructor, increment this counter. Add a class method get_count() that returns the total count. Create 3 Counter objects and print the total count.
Class Variables and Methods
class Counter: count = 0
def __init__(self): Counter.count += 1
@classmethod def get_count(cls): return cls.count
c1 = Counter()c2 = Counter()c3 = Counter()
print(f"Total count: {Counter.get_count()}")Exercise 4: Public and Private Attributes
Create a class called BankAccount with a public attribute account_holder and a private attribute __balance. Add a public method get_balance() that returns the balance. Initialize balance to 0 in the constructor. Read account holder name, create an account, and display the balance.
Public and Private Attributes
class BankAccount: def __init__(self, account_holder): self.account_holder = account_holder self.__balance = 0
def get_balance(self): return self.__balance
name = input()account = BankAccount(name)print(f"Account Holder: {account.account_holder}")print(f"Balance: {account.get_balance()}")Exercise 5: Properties
Create a class called Temperature with a private attribute _celsius. Use properties to get and set celsius, ensuring it cannot be set below -273.15. Read initial temperature, then a new temperature, and display both.
Properties
class Temperature: def __init__(self, celsius): self._celsius = celsius
@property def celsius(self): return self._celsius
@celsius.setter def celsius(self, value): if value >= -273.15: self._celsius = value
initial = float(input())new_temp = float(input())
temp = Temperature(initial)print(f"Initial: {temp.celsius}°C")temp.celsius = new_tempprint(f"New: {temp.celsius}°C")Exercise 6: Special Methods - __str__ and __repr__
Create a class called Point with x and y coordinates. Implement __str__ to return “Point(x, y)” and __repr__ to return “Point(x, y)”. Read x and y, create a Point, and print it using both str and repr.
Special Methods
class Point: def __init__(self, x, y): self.x = x self.y = y
def __str__(self): return f"Point({self.x}, {self.y})"
def __repr__(self): return f"Point({self.x}, {self.y})"
x = int(input())y = int(input())point = Point(x, y)print(str(point))print(repr(point))Exercise 7: Special Methods - __eq__
Create a class called Fraction with numerator and denominator. Implement __eq__ to compare two fractions (a/b == c/d if ad == bc). Read two fractions and check if they are equal.
Equality Comparison
class Fraction: def __init__(self, numerator, denominator): self.numerator = numerator self.denominator = denominator
def __eq__(self, other): if isinstance(other, Fraction): return (self.numerator * other.denominator == self.denominator * other.numerator) return False
num1 = int(input())den1 = int(input())num2 = int(input())den2 = int(input())
f1 = Fraction(num1, den1)f2 = Fraction(num2, den2)print(f1 == f2)Exercise 8: Basic Inheritance
Create a parent class Vehicle with brand and model attributes, and a start() method that returns “Vehicle started”. Create a child class Car that inherits from Vehicle and adds a honk() method. Read brand and model, create a Car, and call both methods.
Basic Inheritance
class Vehicle: def __init__(self, brand, model): self.brand = brand self.model = model
def start(self): return "Vehicle started"
class Car(Vehicle): def honk(self): return "Beep beep!"
brand = input()model = input()car = Car(brand, model)print(car.start())print(car.honk())Exercise 9: Method Overriding
Create a parent class Shape with an area() method that returns 0. Create child classes Rectangle and Circle that override area() to calculate their respective areas. Read values and create objects, then print their areas.
Method Overriding
import math
class Shape: def area(self): return 0
class Rectangle(Shape): def __init__(self, length, width): self.length = length self.width = width
def area(self): return self.length * self.width
class Circle(Shape): def __init__(self, radius): self.radius = radius
def area(self): return math.pi * self.radius ** 2
length = float(input())width = float(input())radius = float(input())
rect = Rectangle(length, width)circle = Circle(radius)
print(f"Rectangle area: {rect.area()}")print(f"Circle area: {circle.area():.2f}")Exercise 10: Using super()
Create a parent class Person with name and age, and a display() method. Create a child class Student that adds student_id and overrides display() to include student_id using super(). Read values and create a Student, then display.
Using super()
class Person: def __init__(self, name, age): self.name = name self.age = age
def display(self): return f"Name: {self.name}, Age: {self.age}"
class Student(Person): def __init__(self, name, age, student_id): super().__init__(name, age) self.student_id = student_id
def display(self): return f"{super().display()}, Student ID: {self.student_id}"
name = input()age = int(input())student_id = input()
student = Student(name, age, student_id)print(student.display())Exercise 11: Multiple Inheritance
Create two parent classes: Flyable with a fly() method returning “Flying!” and Swimmable with a swim() method returning “Swimming!”. Create a child class Duck that inherits from both and has a name attribute. Read name and call all three methods.
Multiple Inheritance
class Flyable: def fly(self): return "Flying!"
class Swimmable: def swim(self): return "Swimming!"
class Duck(Flyable, Swimmable): def __init__(self, name): self.name = name
def quack(self): return f"{self.name} quacks!"
name = input()duck = Duck(name)print(duck.fly())print(duck.swim())print(duck.quack())Exercise 12: Polymorphism with Duck Typing
Create three classes Dog, Cat, and Bird, each with a speak() method. Create a function make_animal_speak() that takes any object with a speak() method and calls it. Test with all three classes.
Polymorphism with Duck Typing
class Dog: def speak(self): return "Woof!"
class Cat: def speak(self): return "Meow!"
class Bird: def speak(self): return "Chirp!"
def make_animal_speak(animal): return animal.speak()
dog = Dog()cat = Cat()bird = Bird()
print(make_animal_speak(dog))print(make_animal_speak(cat))print(make_animal_speak(bird))Exercise 13: Abstract Base Class
Create an abstract base class Shape with abstract methods area() and perimeter(). Create concrete classes Rectangle and Circle that implement these methods. Read values and display areas and perimeters.
Abstract Base Class
from abc import ABC, abstractmethodimport math
class Shape(ABC): @abstractmethod def area(self): pass
@abstractmethod def perimeter(self): pass
class Rectangle(Shape): def __init__(self, length, width): self.length = length self.width = width
def area(self): return self.length * self.width
def perimeter(self): return 2 * (self.length + self.width)
class Circle(Shape): def __init__(self, radius): self.radius = radius
def area(self): return math.pi * self.radius ** 2
def perimeter(self): return 2 * math.pi * self.radius
length = float(input())width = float(input())radius = float(input())
rect = Rectangle(length, width)circle = Circle(radius)
print(f"Rectangle - Area: {rect.area()}, Perimeter: {rect.perimeter()}")print(f"Circle - Area: {circle.area():.2f}, Perimeter: {circle.perimeter():.2f}")Exercise 14: Composition
Create an Engine class with a start() method returning “Engine started”. Create a Car class that has an Engine (composition). Create a Car and start its engine, then print “Car is ready!”.
Composition
class Engine: def start(self): return "Engine started"
class Car: def __init__(self): self.engine = Engine()
def start_car(self): return self.engine.start()
car = Car()print(car.start_car())print("Car is ready!")Exercise 15: Complete Bank Account System
Create a BankAccount class with private __balance, public account_holder, class variable account_count, and methods: deposit(amount), withdraw(amount), get_balance(). Use a class method to get account count. Read account holder name and initial balance, deposit 100, withdraw 50, then display balance and account count.
Complete Bank Account System
class BankAccount: account_count = 0
def __init__(self, account_holder, initial_balance=0): self.account_holder = account_holder self.__balance = initial_balance BankAccount.account_count += 1
def deposit(self, amount): if amount > 0: self.__balance += amount
def withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount
def get_balance(self): return self.__balance
@classmethod def get_account_count(cls): return cls.account_count
name = input()initial = float(input())
account = BankAccount(name, initial)account.deposit(100)account.withdraw(50)
print(f"Balance: {account.get_balance()}")print(f"Total accounts: {BankAccount.get_account_count()}")Exercise 16: Operator Overloading
Create a Vector class with x and y coordinates. Implement __add__ to add two vectors and __str__ to display as “Vector(x, y)”. Read two vectors, add them, and print the result.
Operator Overloading
class Vector: def __init__(self, x, y): self.x = x self.y = y
def __add__(self, other): return Vector(self.x + other.x, self.y + other.y)
def __str__(self): return f"Vector({self.x}, {self.y})"
x1 = int(input())y1 = int(input())x2 = int(input())y2 = int(input())
v1 = Vector(x1, y1)v2 = Vector(x2, y2)v3 = v1 + v2
print(v3)Exercise 17: Data Class
Create a data class Student with fields name, age, and grade. Create two Student objects with the same values and one with different values. Test equality comparison and print the results.
Data Class
from dataclasses import dataclass
@dataclassclass Student: name: str age: int grade: int
name1 = input()age1 = int(input())grade1 = int(input())name2 = input()age2 = int(input())grade2 = int(input())
student1 = Student(name1, age1, grade1)student2 = Student(name1, age1, grade1)student3 = Student(name2, age2, grade2)
print(student1 == student2)print(student1 == student3)Exercise 18: Complex Inheritance Hierarchy
Create a base class Animal with name and make_sound() method. Create Mammal that inherits from Animal and adds fur_color. Create Dog that inherits from Mammal and overrides make_sound() to return “Woof!”. Read name and fur_color, create a Dog, and display all information.
Complex Inheritance Hierarchy
class Animal: def __init__(self, name): self.name = name
def make_sound(self): return "Some sound"
class Mammal(Animal): def __init__(self, name, fur_color): super().__init__(name) self.fur_color = fur_color
class Dog(Mammal): def make_sound(self): return "Woof!"
name = input()fur_color = input()
dog = Dog(name, fur_color)print(f"Name: {dog.name}")print(f"Fur Color: {dog.fur_color}")print(f"Sound: {dog.make_sound()}")Exercise 19: Special Methods - Comparison
Create a Student class with name and grade. Implement __lt__ to compare students by grade. Read two students, compare them, and print which student has a higher grade.
Comparison Operators
class Student: def __init__(self, name, grade): self.name = name self.grade = grade
def __lt__(self, other): return self.grade < other.grade
name1 = input()grade1 = int(input())name2 = input()grade2 = int(input())
student1 = Student(name1, grade1)student2 = Student(name2, grade2)
if student1 < student2: print(f"{student2.name} has a higher grade")else: print(f"{student1.name} has a higher grade")Exercise 20: Complete OOP System
Create a library system: Abstract base class Item with abstract get_info(), concrete classes Book and Magazine that inherit from Item, and a Library class that uses composition to store items. Add methods to add items and display all items. Read book and magazine info, add them to library, and display all.
Complete OOP System
from abc import ABC, abstractmethod
class Item(ABC): def __init__(self, title, author): self.title = title self.author = author
@abstractmethod def get_info(self): pass
class Book(Item): def get_info(self): return f"Book: {self.title} by {self.author}"
class Magazine(Item): def get_info(self): return f"Magazine: {self.title} by {self.author}"
class Library: def __init__(self): self.items = []
def add_item(self, item): self.items.append(item)
def display_all(self): for item in self.items: print(item.get_info())
book_title = input()book_author = input()mag_title = input()mag_author = input()
library = Library()library.add_item(Book(book_title, book_author))library.add_item(Magazine(mag_title, mag_author))library.display_all()