12 Python Object Oriented Programming (OOP) Exercises

python-object-oriented-programming-oop-exercises-questions-with-solutions

If you’re looking to enhance your Python skills and dive into the world of Object-Oriented Programming (OOP), you’re in the right place. In this article, we’ll explore a range of Python OOP exercises to help you grasp the fundamentals and sharpen your coding skills.

Course for You: Python OOP Course: Master Object-Oriented Programming

Why Object-Oriented Programming?

Before we jump into the exercises, let’s briefly understand why OOP is essential in Python (and any programming in general). OOP is a programming concept or style that allows you to structure your code in a more organized and efficient way.

It promotes the concept of objects and classes, making code more modular, reusable, and easier to maintain. Learning OOP in Python can be a game-changer for your programming journey.

Exercise 1: Creating a Class and Object

Create a Python class called “Car” with attributes like make, model, and year. Then, create an object of the “Car” class and print its details.

# python oop exercises: Create a simple a Class and Object
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

my_car = Car("Toyota", "Camry", 2022)
print(f"My car is a {my_car.year} {my_car.make} {my_car.model}.")
My car is a 2022 Toyota Camry.

Exercise 2: Inheritance

Create a base class called “Animal” and two subclasses, “Dog” and “Cat.” Add methods and attributes specific to each subclass.

# oop python exercises: Inheritance, Sub-Class
class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def sound(self):
        return "Woof!"

class Cat(Animal):
    def sound(self):
        return "Meow!"
    
# Create instances of Dog and Cat
dog_instance = Dog("Buddy")
cat_instance = Cat("Whiskers")

# Call the sound method on the instances
dog_sound = dog_instance.sound()
cat_sound = cat_instance.sound()

# Print the output
print(f"{dog_instance.name} says: {dog_sound}")
print(f"{cat_instance.name} says: {cat_sound}")

This code will create instances of Dog and Cat, call the sound method on each instance, and then print the output, which will display the sounds made by each animal:

Buddy says: Woof!
Whiskers says: Meow!

Exercise 3: Polymorphism

Create a function that takes an animal object as input and calls its “sound” method. Test it with both a dog and a cat object. Utilize same class mentioned in the above (Exercise 2) Python code.

# python oop exercises with solutions: Polymorphism
def animal_sound(animal):
    return animal.sound()

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(f"{dog.name} says: {animal_sound(dog)}")
print(f"{cat.name} says: {animal_sound(cat)}")
Buddy says: Woof!
Whiskers says: Meow!

Exercise 4: Multiple Inheritance

Create three classes, “Person,” “Employee,” and “Student.” Use multiple inheritance to create a class “PersonInfo” that inherits from both “Employee” and “Student.” Add attributes and methods specific to each class.

# oop exercises python: Multiple Inheritance
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Employee:
    def __init__(self, emp_id, salary):
        self.emp_id = emp_id
        self.salary = salary

class Student:
    def __init__(self, student_id, grade):
        self.student_id = student_id
        self.grade = grade

class PersonInfo(Person, Employee, Student):
    def __init__(self, name, age, emp_id, salary, student_id, grade):
        Person.__init__(self, name, age)
        Employee.__init__(self, emp_id, salary)
        Student.__init__(self, student_id, grade)

# Create an instance of PersonInfo
person_info = PersonInfo("John", 30, "E123", 50000, "S456", "A")

# Access the attributes
print(f"Name: {person_info.name}")
print(f"Age: {person_info.age}")
print(f"Employee ID: {person_info.emp_id}")
print(f"Salary: {person_info.salary}")
print(f"Student ID: {person_info.student_id}")
print(f"Grade: {person_info.grade}")
Name: John
Age: 30
Employee ID: E123
Salary: 50000
Student ID: S456
Grade: A

This code creates an instance of PersonInfo then prints out the attributes of that instance, displaying the information for a person who is also an employee and a student.

Also Read:  19 Python Programming Lists Practice Exercises

Exercise 5: Abstract Base Classes

Create an abstract base class called “Shape” with an abstract method called “area.” Implement two subclasses, “Circle” and “Rectangle,” that inherit from “Shape” and provide their own implementations of the “area” method.

# exercises on oop python: Abstract Base Classes
from abc import ABC, abstractmethod
import math

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

# Create instances of Circle and Rectangle
circle = Circle(5)
rectangle = Rectangle(4, 6)

# Call the area method on the instances
circle_area = circle.area()
rectangle_area = rectangle.area()

# Print the areas
print(f"Circle Area: {circle_area}")
print(f"Rectangle Area: {rectangle_area}")

This code creates instances of Circle and Rectangle, calls their area methods to calculate the area of each shape, and then print out the calculated areas.

Circle Area: 78.53981633974483
Rectangle Area: 24

Exercise 6: Class Methods and Static Methods

Create a class called “MathUtils” with class methods for calculating the factorial of a number and a static method to check if a number is even.

# python oop exercises questions: Class Methods and Static Methods
class MathUtils:
    @classmethod
    def factorial(cls, n):
        if n == 0:
            return 1
        else:
            return n * cls.factorial(n - 1)

    @staticmethod
    def is_even(number):
        return number % 2 == 0

# Calculate factorial (Class Method)
print(MathUtils.factorial(5))  

# Check if a number is even (Static Method)
print(MathUtils.is_even(10))      
120
True

Exercise 7: Composition

In this Python (object oriented programming) oop exercises create classes for “Author” and “Book.” The “Book” class should have an “Author” object as an attribute, demonstrating composition.

# python oop exercises questions pdf: Composition
class Author:
    def __init__(self, name, nationality):
        self.name = name
        self.nationality = nationality

class Book:
    def __init__(self, title, author, publication_year):
        self.title = title
        self.author = author
        self.publication_year = publication_year

# Example usage
author1 = Author("J.K. Rowling", "British")
book1 = Book("Harry Potter and the Sorcerer's Stone", author1, 1997)

# Access and print the information
print(f"Author: {author1.name}")
print(f"Nationality: {author1.nationality}")
print(f"Book Title: {book1.title}")
print(f"Publication Year: {book1.publication_year}")
Author: J.K. Rowling
Nationality: British
Book Title: Harry Potter and the Sorcerer's Stone
Publication Year: 1997

Exercise 8: Operator Overloading

In this Python OOP exercises let’s use a simple example of operator overloading by creating a Point class that overloads the + operator to add two points together.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        # Overload the '+' operator to add two Point objects
        new_x = self.x + other.x
        new_y = self.y + other.y
        return Point(new_x, new_y)

    def __str__(self):
        return f"Point({self.x}, {self.y})"

# Create two Point objects
point1 = Point(1, 2)
point2 = Point(3, 4)

# Use the overloaded '+' operator to add points
result = point1 + point2

# Print the results
print(f"point1: {point1}")
print(f"point2: {point2}")
print(f"point1 + point2: {result}")
point1: Point(1, 2)
point2: Point(3, 4)
point1 + point2: Point(4, 6)

Exercise 9: Exception Handling in OOP

In this oops exercise create a class called “Calculator” with methods for addition, subtraction, multiplication, and division. Handle exceptions like division by zero gracefully and raise custom exceptions when needed.

# python oop exercises questions: Exception Handling
class Calculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        if b == 0:
            raise ZeroDivisionError("Division by zero is not allowed")
        return a / b

calculator = Calculator()
result = calculator.divide(10, 0)  # Handle division by zero
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-37-f3bedfbfe1d0> in <module>()
     16 
     17 calculator = Calculator()
---> 18 result = calculator.divide(10, 0)  # Handle division by zero

<ipython-input-37-f3bedfbfe1d0> in divide(self, a, b)
     12     def divide(self, a, b):
     13         if b == 0:
---> 14             raise ZeroDivisionError("Division by zero is not allowed")
     15         return a / b
     16 

ZeroDivisionError: Division by zero is not allowed

Exercise 10: Composition with Aggregation

In this Python oop exercise, create classes for “Department” and “Employee.” Use aggregation to represent that an Employee belongs to a Department. Implement methods to add employees to a department and calculate the average salary of employees in a department.

# Python object oriented programming (oop) exercises: Composition with Aggregation
class Department:
    def __init__(self, name):
        self.name = name
        self.employees = []

    def add_employee(self, employee):
        self.employees.append(employee)

    def average_salary(self):
        if not self.employees:
            return 0
        total_salary = sum(employee.salary for employee in self.employees)
        return total_salary / len(self.employees)

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

hr_department = Department("HR")
hr_department.add_employee(Employee("Alice", 50000))
hr_department.add_employee(Employee("Bob", 60000))

print(f"Average salary in {hr_department.name} department: ${hr_department.average_salary()}")
Average salary in HR department: $55000.0

Exercise 11: Method Overriding

Create a base class called “Vehicle” with a method called “drive.” Implement two subclasses, “Car” and “Bicycle,” that inherit from “Vehicle” and override the “drive” method with their own implementations.

# python oop (object oriented programming) exercises questions: Method Overriding
class Vehicle:
    def drive(self):
        return "Driving a generic vehicle"

class Car(Vehicle):
    def drive(self):
        return "Driving a car"

class Bicycle(Vehicle):
    def drive(self):
        return "Riding a bicycle"

car = Car()
bicycle = Bicycle()

print(car.drive())       # Output: "Driving a car"
print(bicycle.drive())   # Output: "Riding a bicycle"
Driving a car
Riding a bicycle

Exercise 12: Metaclasses

In this Python exercise program solution create a metaclass called “SingletonMeta” that ensures only one instance of a class is created. Use this metaclass to create a “Singleton” class that demonstrates the Singleton pattern.

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class Singleton(metaclass=SingletonMeta):
    def __init__(self, value):
        self.value = value

singleton1 = Singleton("First Instance")
singleton2 = Singleton("Second Instance")

print(singleton1.value)  # Output: "First Instance"
print(singleton2.value)  # Output: "First Instance" (same instance)

In this article, I have listed some example exercises and program questions to practice Object oriented programming (OOP) concept in Python, you can make a pdf and practice it any time. If you are not able to understand the examples listed in this article, that means your OOP concept is not clear.

Also Read:  21 Python String Exercises for Beginners

For that, I will suggest you this Udemy course: Python OOP Course: Master Object-Oriented Programming. If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python.

This is it for this article. If you have any questions or suggestions regarding this article, please let me know in the comment section below.

Similar Read:

Leave a comment