Python Abstract Classes and Methods

Introduction

Abstract classes and methods are fundamental concepts in object-oriented programming (OOP) that allow you to define methods that must be implemented by derived classes. Abstract classes serve as blueprints for other classes and cannot be instantiated on their own. They are particularly useful when you want to provide a common interface for a group of subclasses.

Key Concepts

Abstract Class

An abstract class is a class that contains one or more abstract methods. It cannot be instantiated directly and is intended to be subclassed.

Abstract Method

An abstract method is a method that is declared in an abstract class but does not have any implementation. Subclasses of the abstract class must provide an implementation for the abstract method.

Syntax

Abstract classes and methods are defined using the abc module in Python.

Defining an Abstract Class

from abc import ABC, abstractmethod

class AbstractClassName(ABC):
    @abstractmethod
    def abstract_method(self):
        pass

Example

Let’s consider a real-world example of a shape drawing system where we have different types of shapes that can be drawn.

Abstract Class: Shape

from abc import ABC, abstractmethod

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

    @abstractmethod
    def area(self):
        pass

Child Classes: Circle and Rectangle

import math

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

    def draw(self):
        return "Drawing a Circle"

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

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

    def draw(self):
        return "Drawing a Rectangle"

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

Using Abstract Classes and Methods

# Creating objects of Circle and Rectangle classes
circle = Circle(5)
rectangle = Rectangle(4, 6)

# Using the methods defined in the abstract class
print(circle.draw())       # Output: Drawing a Circle
print(f"Area: {circle.area()}")  # Output: Area: 78.53981633974483

print(rectangle.draw())    # Output: Drawing a Rectangle
print(f"Area: {rectangle.area()}")  # Output: Area: 24

Explanation

  1. Abstract Class (Shape): Defines the common interface for all shapes with two abstract methods, draw and area.
  2. Child Classes (Circle and Rectangle): Implement the abstract methods draw and area, providing specific behavior for each shape.
  3. Using the Abstract Class: Objects of Circle and Rectangle classes are created, and their methods are called, demonstrating polymorphism and adherence to the common interface defined by the abstract class.

Real-World Example: Employee Management System

Let’s consider a real-world example of an employee management system where we have different types of employees with different methods to calculate their salary.

Abstract Class: Employee

from abc import ABC, abstractmethod

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

    @abstractmethod
    def calculate_salary(self):
        pass

    def get_details(self):
        return f"Employee: {self.name}, ID: {self.employee_id}"

Child Classes: FullTimeEmployee and PartTimeEmployee

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

    def calculate_salary(self):
        return self.salary

class PartTimeEmployee(Employee):
    def __init__(self, name, employee_id, hourly_rate, hours_worked):
        super().__init__(name, employee_id)
        self.hourly_rate = hourly_rate
        self.hours_worked = hours_worked

    def calculate_salary(self):
        return self.hourly_rate * self.hours_worked

Using Abstract Classes and Methods

# Creating objects of FullTimeEmployee and PartTimeEmployee classes
full_time_employee = FullTimeEmployee("Ramesh", "FT123", 60000)
part_time_employee = PartTimeEmployee("Sita", "PT456", 20, 120)

# Using the methods defined in the abstract class
print(full_time_employee.get_details())  # Output: Employee: Ramesh, ID: FT123
print(f"Salary: {full_time_employee.calculate_salary()}")  # Output: Salary: 60000

print(part_time_employee.get_details())  # Output: Employee: Sita, ID: PT456
print(f"Salary: {part_time_employee.calculate_salary()}")  # Output: Salary: 2400

Explanation

  1. Abstract Class (Employee): Defines the common interface for all employees with an abstract method calculate_salary and a concrete method get_details.
  2. Child Classes (FullTimeEmployee and PartTimeEmployee): Implement the abstract method calculate_salary, providing specific behavior for each type of employee.
  3. Using the Abstract Class: Objects of FullTimeEmployee and PartTimeEmployee classes are created, and their methods are called, demonstrating polymorphism and adherence to the common interface defined by the abstract class.

Conclusion

Abstract classes and methods in Python provide a way to define a common interface for a group of subclasses. By using the abc module, you can create abstract classes that cannot be instantiated directly but can be subclassed to provide specific implementations for abstract methods. This helps in designing more flexible and maintainable object-oriented systems. The provided examples of a shape drawing system and an employee management system demonstrate how abstract classes and methods can be effectively applied in real-world scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top