Mastering The Abstraction Class & Interface: A Comprehensive Guide

In Python, abstract classes and interfaces are primarily used to define a blueprint for other classes. They allow you to create a common structure for classes while enforcing specific methods to be implemented in subclasses.

For example, if you want many classes to have a method called speak(), you can create an abstract class with a speak() method that doesn’t do anything yet. Then, any class that uses this abstract class must write its own version of the speak() method.

This is useful because it makes sure all related classes have the same structure and follow the same rules, which helps keep your code organized and easier to understand.

Abstract Class

An abstract class in Python is like a foundation blueprint for building other classes; you can’t create an object from it directly. It can include constructors, variables, abstract methods (which are rules that require subclasses to provide their own versions), and non-abstract methods (which already have code). When you create a new class based on an abstract class, that new class must implement the abstract methods, or it also becomes an abstract class. Essentially, an abstract class sets guidelines for subclasses, ensuring they follow a specific design.

Abstract Method

An abstract method is a method that is defined within an abstract class without any implementation details. Subclasses inheriting from the abstract class are required to provide their own implementation of this method.

Types of Methods in Terms of Implementation:

Implemented Methods:

Implemented methods are regular methods that already have some code written inside them. These methods do something when called — they are not just empty or placeholders like abstract methods.

Example:

class Example:
    def implemented_method(self):
        print("This method is fully implemented.")

Un-implemented Methods (Abstract Methods)

Abstract methods are methods that don’t have any code inside them — they just have a name but no instructions. These methods are like a to-do list for any class that inherits them.

If you create a new class from an abstract class, you must write your own version of these abstract methods.

If you forget to do this, Python won’t let you create objects from that class.

These abstract methods are used to make sure every subclass has certain methods, even if each one works differently.

Example:

from abc import ABC, abstractmethod

class AbstractExample(ABC):
    @abstractmethod
    def unimplemented_method(self):
        pass

Declaring Abstract Methods:

In Python, to declare an abstract method use the @abstractmethod decorator from the abc module. Here’s how to define an abstract class with both abstract and implemented methods:

Example:

from abc import ABC, abstractmethod

class AbstractBank(ABC):
    @abstractmethod
    def calculate_interest(self):
        pass

    def bank_info(self):
        print("Welcome to the bank.")

Example: Implementing an Abstract Class

class SavingsBank(AbstractBank):
    def calculate_interest(self):
        print("Interest for Savings Bank is 5%.")

class CurrentBank(AbstractBank):
    def calculate_interest(self):
        print("Interest for Current Bank is 3%.")

# Create instances of subclasses
savings = SavingsBank()
savings.bank_info()
savings.calculate_interest()

current = CurrentBank()
current.bank_info()
current.calculate_interest()

# Output:
Welcome to the bank.
Interest for Savings Bank is 5%.
Welcome to the bank.
Interest for Current Bank is 3%.

Important Notes

  • Instantiation: You cannot create an instance of an abstract class. Attempting to do so will result in a TypeError.
# This will raise an error
bank = AbstractBank()  # TypeError: Can't instantiate abstract class AbstractBank with abstract methods calculate_interest
  • Subclasses: If a subclass does not implement all abstract methods, it also becomes an abstract class and cannot be instantiated.
  • Multiple Subclasses: An abstract class can be used by many different subclasses. Each subclass must write its own version of the abstract methods.
class HDFCBank(AbstractBank):
    def calculate_interest(self):
        print("Interest for HDFC Bank is 6%.")

Interface

Definition: It is a type of abstract class that contains only abstract methods (methods without a body).

Characteristics

  • In Python, interfaces are created using abstract classes with all abstract methods.
  • Interfaces can contain:
    • Constructors
    • Variables
    • Abstract methods
    • Subclasses
  • If a subclass does not implement all abstract methods of an interface, it becomes an abstract class.
  • Objects cannot be created from an interface; instead, objects can be instantiated from its subclasses that implement the abstract methods.

Key Features of Interfaces in Python

  1. Defining a Contract: Interfaces define methods that must be created within any class that implements the interface, ensuring a consistent API.
  2. Multiple Inheritance: Python allows a class to inherit from multiple interfaces, enabling flexibility in design.
  3. Abstract Base Classes: Interfaces can be implemented using the abc module, which provides the infrastructure for defining abstract base classes.

Concrete Class

  • Definition: A concrete class is a class with all methods fully implemented.
  • When to Use: Use a concrete class when you have complete implementation details.

Usage Guidelines

  • Interface: Use when only requirement specifications are known, with no implementation details.
  • Abstract Class: Use when partial implementation is known but not fully defined.
  • Concrete Class: Use when complete implementation details are available.

Example of an Interface:

from abc import ABC, abstractmethod

# Define an interface using an abstract base class
class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass  # Abstract method

    @abstractmethod
    def habitat(self):
        pass  # Abstract method

# Implementing the interface in subclasses
class Dog(Animal):
    def sound(self):
        return "Bark"  # Implementation of sound method

    def habitat(self):
        return "Domestic"  # Implementation of habitat method

class Cat(Animal):
    def sound(self):
        return "Meow"  # Implementation of sound method

    def habitat(self):
        return "Domestic"  # Implementation of habitat method

# Function to demonstrate polymorphism
def animal_info(animal: Animal):
    print(f"Animal sound: {animal.sound()}")
    print(f"Animal habitat: {animal.habitat()}")

# Creating instances of the subclasses
dog = Dog()
cat = Cat()

# Using the function with different animal types
animal_info(dog)  # Output: Animal sound: Bark, Animal habitat: Domestic
animal_info(cat)  # Output: Animal sound: Meow, Animal habitat: Domestic

When to Use Interfaces

  • Enforcing Method Implementation: Use interfaces when you want to ensure that certain methods are implemented in derived classes.
  • Designing Flexible APIs: Interfaces provide a way to define flexible APIs that can be easily extended or modified without changing existing code.
  • Promoting Polymorphism: Interfaces allow different classes to be treated the same way if they implement the same methods, promoting polymorphism.

Difference Between Abstract Classes and Interfaces

FeatureAbstract ClassesInterfaces
ImplementationCan have both implemented and unimplemented methodsOnly unimplemented methods are defined
Multiple InheritanceCan inherit from multiple abstract classesCan inherit from multiple interfaces
StateCan have state (attributes)Cannot maintain state
ConstructorCan have a constructorCannot have a constructor

Conclusion

Abstract classes and interfaces are essential for achieving polymorphism and designing flexible applications in Python. They help define clear contracts for classes and promote code reuse and maintainability.

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python
Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizo

Related Posts

Leave a Reply

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