close
The Wayback Machine - https://web.archive.org/web/20250115112835/https://www.geeksforgeeks.org/abstract-classes-in-python/
Open In App

Abstract Classes in Python

Last Updated : 13 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, an abstract class is a class that cannot be instantiated on its own and is designed to be a blueprint for other classes. Abstract classes allow us to define methods that must be implemented by subclasses, ensuring a consistent interface while still allowing the subclasses to provide specific implementations.

Abstract Base Classes in Python

It defines methods that must be implemented by its subclasses, ensuring that the subclasses follow a consistent structure. ABCs allow you to define common interfaces that various subclasses can implement while enforcing a level of abstraction.

Python provides the abc module to define ABCs and enforce the implementation of abstract methods in subclasses.

Example:

Python
from abc import ABC, abstractmethod

# Define an abstract class
class Animal(ABC):
    
    @abstractmethod
    def sound(self):
        pass  # This is an abstract method, no implementation here.

# Concrete subclass of Animal
class Dog(Animal):
    
    def sound(self):
        return "Bark"  # Providing the implementation of the abstract method

# Create an instance of Dog
dog = Dog()
print(dog.sound())  # Output: Bark

Code Explanation:

  • Abstract Base Class: Animal is an abstract class that inherits from ABC (Abstract Base Class). This class cannot be instantiated directly because it contains an abstract method sound(). The @abstractmethod decorator is used to mark sound() as an abstract method. This means any subclass must implement this method to be instantiated.
  • Concrete Subclass: Dog is a subclass of Animal that provides an implementation for the sound() method. This allows the Dog class to be instantiated and used.
  • Instantiation: We create an instance of Dog and call the sound() method, which returns “Bark”.

The main components of an abstract class are:

Abstract Methods

Abstract methods are methods that are defined in an abstract class but do not have an implementation. They serve as a blueprint for the subclasses, ensuring that they provide their own implementation.

Example:

Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass  # Abstract method, no implementation here

Explanation:

  • make_sound() is an abstract method in the Animal class, so it doesn’t have any code inside it.

Concrete Methods

Concrete methods are methods that have full implementations in an abstract class. These methods can be inherited by subclasses and used directly without needing to be redefined.

Example:

Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass  # Abstract method, to be implemented by subclasses

    def move(self):
        return "Moving"  # Concrete method with implementation

Explanation:

  • The move() method is a concrete method in the Animal class. It is implemented and does not need to be overridden by the Dog class.

Abstract Properties

Abstract properties work like abstract methods but are used for properties. These properties are declared with the @property decorator and marked as abstract using @abstractmethod. Subclasses must implement these properties.

Example:

Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @property
    @abstractmethod
    def species(self):
        pass  # Abstract property, must be implemented by subclasses

class Dog(Animal):
    @property
    def species(self):
        return "Canine"

# Instantiate the concrete subclass
dog = Dog()
print(dog.species)

Explanation:

  • species is an abstract property in the Animal class and it is marked as @abstractmethod.
  • The Dog class implements the species property, making it a concrete subclass that can be instantiated.
  • Abstract properties enforce that a subclass provides the property’s implementation.

Abstract Class Instantiation

Abstract classes cannot be instantiated directly. This is because they contain one or more abstract methods or properties that lack implementations. Attempting to instantiate an abstract class results in a TypeError.

Example:

Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

# Trying to instantiate the abstract class directly
# This will raise an error:
# animal = Animal()  # TypeError: Can't instantiate abstract class Animal with abstract methods make_sound

Explanation:

  • The Animal class is abstract because it has the make_sound() method as an abstract method.
  • If you try to instantiate Animal directly (e.g., animal = Animal()), Python raises a TypeError because you can’t instantiate a class with unimplemented abstract methods.
  • Only subclasses that implement all abstract methods can be instantiated.

Abstract Classes in Python – FAQs

What is the Purpose of Abstract Classes in Python?

Abstract classes in Python are used to define a common interface for a group of subclasses. They enforce certain methods to be implemented by any subclass, ensuring a consistent API and encouraging code reuse. Abstract classes themselves cannot be instantiated and are meant to be inherited by other classes that provide concrete implementations of the abstract methods.

How to Define and Use an Abstract Class in Python?

To define an abstract class in Python, you typically use the abc (Abstract Base Class) module. An abstract class is defined by inheriting from ABC and using the @abstractmethod decorator to define abstract methods that must be implemented by subclasses.

Example:

from abc import ABC, abstractmethod

class Animal(ABC):
@abstractmethod
def sound(self):
pass

class Dog(Animal):
def sound(self):
return "Bark"

dog = Dog()
print(dog.sound()) # Output: Bark

What is the ‘abc' Module and How is It Used in Python?

The abc module in Python provides tools for defining abstract base classes. It includes the ABC class and the abstractmethod decorator, which are used to create abstract classes and methods.

Using the abc Module:

from abc import ABC, abstractmethod

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

class Rectangle(Shape):
def area(self):
return 10 * 20

rectangle = Rectangle()
print(rectangle.area()) # Output: 200

How to Define Abstract Methods in Python?

Abstract methods in Python are defined using the @abstractmethod decorator from the abc module. These methods do not provide any implementation in the abstract class and must be overridden in any concrete subclass.

Example:

from abc import ABC, abstractmethod

class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass

class Car(Vehicle):
def start_engine(self):
return "Car engine started"

car = Car()
print(car.start_engine()) # Output: Car engine started

Why Should Abstract Classes Be Used in Python?

Abstract classes should be used in Python for several reasons:

  1. Enforcing a Contract: Ensure that all subclasses implement certain methods, providing a consistent interface.
  2. Code Reusability: Define common functionality in the abstract class and reuse it in all subclasses.
  3. Encouraging Design Principles: Promote the use of design patterns and principles like SOLID.
  4. Reducing Code Duplication: Define shared methods and properties once in the abstract class.
  5. Improved Readability and Maintainability: Provide clear guidelines for developers about the structure and behavior expected from subclasses

Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article

Similar Reads

three90RightbarBannerImg