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

Abstract Classes in Python

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

An abstract class can be considered a blueprint for other classes. It allows you to create a set of methods that must be created within any child classes built from the abstract class.

A class that contains one or more abstract methods is called an abstract class. An abstract method is a method that has a declaration but does not have an implementation.

We use an abstract class while we are designing large functional units or when we want to provide a common interface for different implementations of a component. 

Abstract Base Classes in Python

By defining an abstract base class, you can define a common Application Program Interface(API) for a set of subclasses. This capability is especially useful in situations where a third party is going to provide implementations, such as with plugins, but can also help you when working in a large team or with a large code base where keeping all classes in your mind is difficult or not possible. 

Working on Python Abstract classes 

By default, Python does not provide abstract classes. Python comes with a module that provides the base for defining Abstract Base classes(ABC) and that module name is ABC.

ABC works by decorating methods of the base class as an abstract and then registering concrete classes as implementations of the abstract base. A method becomes abstract when decorated with the keyword @abstractmethod.

Example 1:

This code defines an abstract base class called “Polygon” using the ABC (Abstract Base Class) module in Python. The “Polygon” class has an abstract method called “noofsides” that needs to be implemented by its subclasses.

There are four subclasses of “Polygon” defined: “Triangle,” “Pentagon,” “Hexagon,” and “Quadrilateral.” Each of these subclasses overrides the “noofsides” method and provides its own implementation by printing the number of sides it has.

In the driver code, instances of each subclass are created, and the “noofsides” method is called on each instance to display the number of sides specific to that shape.

Python
# Python program showing
# abstract base class work
from abc import ABC, abstractmethod


class Polygon(ABC):

    @abstractmethod
    def noofsides(self):
        pass


class Triangle(Polygon):

    # overriding abstract method
    def noofsides(self):
        print("I have 3 sides")


class Pentagon(Polygon):

    # overriding abstract method
    def noofsides(self):
        print("I have 5 sides")


class Hexagon(Polygon):

    # overriding abstract method
    def noofsides(self):
        print("I have 6 sides")


class Quadrilateral(Polygon):

    # overriding abstract method
    def noofsides(self):
        print("I have 4 sides")


# Driver code
R = Triangle()
R.noofsides()

K = Quadrilateral()
K.noofsides()

R = Pentagon()
R.noofsides()

K = Hexagon()
K.noofsides()

Output
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides


Example 2: 

Here, This code defines an abstract base class called “Animal” using the ABC (Abstract Base Class) module in Python. The “Animal” class has a non-abstract method called “move” that does not have any implementation. There are four subclasses of “Animal” defined: “Human,” “Snake,” “Dog,” and “Lion.” Each of these subclasses overrides the “move” method and provides its own implementation by printing a specific movement characteristic.

Python
# Python program showing
# abstract base class work
from abc import ABC, abstractmethod


class Animal(ABC):

    def move(self):
        pass

class Human(Animal):

    def move(self):
        print("I can walk and run")

class Snake(Animal):

    def move(self):
        print("I can crawl")

class Dog(Animal):

    def move(self):
        print("I can bark")

class Lion(Animal):

    def move(self):
        print("I can roar")

# Driver code
R = Human()
R.move()

K = Snake()
K.move()

R = Dog()
R.move()

K = Lion()
K.move()

Output
I can walk and run
I can crawl
I can bark
I can roar


Implementation of Abstract through Subclass

By subclassing directly from the base, we can avoid the need to register the class explicitly. In this case, the Python class management is used to recognize Plugin implementation as implementing the abstract PluginBase. 

Python
# Python program showing
# implementation of abstract
# class through subclassing
import abc

class parent:       
    def geeks(self):
        pass

class child(parent):
    def geeks(self):
        print("child class")

# Driver code
print( issubclass(child, parent))
print( isinstance(child(), parent))

Output
True
True


A side-effect of using direct subclassing is, it is possible to find all the implementations of your plugin by asking the base class for the list of known classes derived from it. 

Concrete Methods in Abstract Base Classes

Concrete classes contain only concrete (normal) methods whereas abstract classes may contain both concrete methods and abstract methods.

The concrete class provides an implementation of abstract methods, the abstract base class can also provide an implementation by invoking the methods via super(). Let look over the example to invoke the method using super():  

Python
# Python program invoking a 
# method using super()
from abc import ABC

class R(ABC):
    def rk(self):
        print("Abstract Base Class")

class K(R):
    def rk(self):
        super().rk()
        print("subclass ")

# Driver code
r = K()
r.rk()

Output
Abstract Base Class
subclass 


In the above program, we can invoke the methods in abstract classes by using super(). 

Abstract Properties in Python

Abstract classes include attributes in addition to methods, you can require the attributes in concrete classes by defining them with @abstractproperty. 

Python
# Python program showing
# abstract properties

import abc
from abc import ABC, abstractmethod


class parent(ABC):
    @abc.abstractproperty
    def geeks(self):
        return "parent class"


class child(parent):

    @property
    def geeks(self):
        return "child class"


try:
    r = parent()
    print(r.geeks)
except Exception as err:
    print(err)

r = child()
print(r.geeks)

Output
Can't instantiate abstract class parent with abstract methods geeks
child class


In the above example, the Base class cannot be instantiated because it has only an abstract version of the property-getter method. 

Abstract Class Instantiation

Abstract classes are incomplete because they have methods that have nobody. If Python allows creating an object for abstract classes then using that object if anyone calls the abstract method, but there is no actual implementation to invoke.

So, we use an abstract class as a template and according to the need, we extend it and build on it before we can use it. Due to the fact, an abstract class is not a concrete class, it cannot be instantiated. When we create an object for the abstract class it raises an error. 

Python
# Python program showing
# abstract class cannot
# be an instantiation
from abc import ABC,abstractmethod

class Animal(ABC):
    @abstractmethod
    def move(self):
        pass
class Human(Animal):
    def move(self):
        print("I can walk and run")

class Snake(Animal):
    def move(self):
        print("I can crawl")

class Dog(Animal):
    def move(self):
        print("I can bark")

class Lion(Animal):
    def move(self):
        print("I can roar")

c=Animal()

Output:

Traceback (most recent call last):
File "/home/ffe4267d930f204512b7f501bb1bc489.py", line 19, in
c=Animal()
TypeError: Can't instantiate abstract class Animal with abstract methods move

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


Similar Reads

Abstract Base Class (abc) in Python
Have you ever thought about checking whether the objects you are using adheres to a particular specification? It is necessary to verify whether an object implements a given method or property, especially while creating a library where other developers make use of it. A developer can use hasattr or isinstance methods to check whether the input confo
7 min read
Implementing Web Crawler using Abstract Factory Design Pattern in Python
In the Abstract Factory design pattern, every product has an abstract product interface. This approach facilitates the creation of families of related objects that is independent of their factory classes. As a result, you can change the factory at runtime to get a different object – simplifies the replacement of the product families. In this design
5 min read
Difference between abstract class and interface in Python
In this article, we are going to see the difference between abstract classes and interface in Python, Below are the points that are discussed in this article: What is an abstract class in Python?What is an interface in Python?Difference between abstract class and interface in PythonWhat is an Abstract class in Python? A blueprint for other classes
4 min read
PyQt5 QCalendarWidget - Setting Border to the Abstract View
In this article we will see how we can set border to the abstract view of the QCalendarWidget. In calendar abstract view is the view that consist the dates inside it, setting border to QCalendarWidget is not like setting border to the other widgets, calendar is widget which has many child i.e component we can set border to independent component as
2 min read
PyQt5 QCalendarWidget - Background Color to the Abstract View
In this article we will see how we can set background color to the abstract view of the QCalendarWidget. In calendar abstract view is the view that consist the dates inside it, setting background color to QCalendarWidget is not like setting background color to the other widgets, calendar is widget which has many child i.e component we can set backg
2 min read
How to create Abstract Model Class in Django?
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. What is model Inheritance? Model Inheritance in Dja
2 min read
Data Classes in Python | An Introduction
dataclass module is introduced in Python 3.7 as a utility tool to make structured classes specially for storing data. These classes hold certain properties and functions to deal specifically with the data and its representation.DataClasses in widely used Python3.6 Although the module was introduced in Python3.7, one can also use it in Python3.6 by
3 min read
Data Classes in Python | Set 2 (Decorator Parameters)
Prerequisite: Data Classes in Python | Set 1 In this post, we will discuss how to modify the default constructor which dataclass module virtually makes for us. dataclass() decorator - @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) By changing the values of these parameters, we can modify the b
4 min read
Data Classes in Python | Set 3 (dataclass fields)
Prerequisite: Data Classes in Python Set 1 | Set 2 In this post we will discuss how to modify certain properties of the attributes of DataClass object, without explicitly writing code for it using field function. field() function - dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata
4 min read
Data Classes in Python | Set 4 (Inheritance)
Prerequisites: Inheritance In Python, Data Classes in Python | Set 3 In this post, we will discuss how DataClasses behave when inherited. Though they make their own constructors, DataClasses behave pretty much the same way as normal classes do when inherited. from dataclasses import dataclass @dataclass class Article: title: str content: str author
2 min read
Data Classes in Python | Set 5 (post-init)
Prerequisite: Data Classes in Python | Set 4 In this post, we will discuss how to modify values of some attributes during object creation without coding it in __init__() by using post-init processing. __post_init__(): This function when made, is called by in-built __init__() after initialization of all the attributes of DataClass. Basically, object
2 min read
Data Classes in Python | Set 6 (interconversion to and from other datatypes)
Prerequisite: Data Classes in Python | Set 5 In the last post of DataClass series, we will discuss how to get values of a DataClass object into a dictionary or tuple pairs and how to create a DataClass in a different way - from values, instead of defining it directly. asdict() function - dataclasses.asdict(instance, *, dict_factory=dict) One can si
2 min read
How to Dynamically Load Modules or Classes in Python
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of importing a module is shown below in which, there are
3 min read
Create Classes Dynamically in Python
A class defines a collection of instance variables and methods to specify an object type. A class can be used to make as many object instances of the type of object as needed. An object is an identified entity with certain attributes (data members) and behaviours (member functions). Group of objects having similar characteristics and behaviour are
2 min read
The Ultimate Guide to Data Classes in Python 3.7
This article discusses data classes in Python 3.7 and provides an introductory guide for data classes in Python 3.7 and above. Data Class is a new concept introduced in Python 3.7 version. You can use data classes not only as a knowledge container but also to write boiler-plate code for you and simplify the process of creating classes since it come
4 min read
SQLAlchemy - Mapping Python Classes
SQLAlchemy is a popular Python library that provides a nice API for interacting with databases. One of its key features is the ability to map Python classes to database tables, allowing you to use Python objects to represent rows in a database table. This is known as an "object-relational mapper" (ORM). Types of Mappings in Python Classes In SQLAlc
7 min read
Comparing Old-Style and New-Style Classes in Python
In Python, the difference between old-style and new-style classes is based on the inheritance from the built-in object class. This distinction was introduced in Python 2.x and was fully adopted in Python 3.x, where all classes are new-style classes. In this article, we will see the difference between the old-style and new-style classes in Python. P
4 min read
Why do Python classes inherit object?
In Python, every class you create inherits from a special class known as an object. This foundational element simplifies and empowers Python programming. When a new class is defined without specifying a superclass, Python assumes that it inherits from the object class. This is referred to as a "new-style" class declaration and was introduced in Pyt
3 min read
Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it to maintain its state. Class instances can als
11 min read
Scala | Value Classes
Value classes are a new mechanism which help to avoid allocating run time objects. AnyVal define value classes. Value classes are predefined, they coincide to the primitive kind of Java-like languages. There are nine predefined value types : Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. equals or hashCode cannot redefine by a valu
2 min read
Don't Let Your Geographical Location Be A Barrier In Your Success - Live Classes By GeeksforGeeks
Winter is coming and so is the placement season! And there are many companies that recruit during this time including product-based companies, startups or service-based companies. So if you want to succeed and bag your dream job, thorough interview preparation is a must!!! Now I am sure interviews scare you a lot, just like most candidates!!! But y
6 min read
How to Handle Imbalanced Classes in Machine Learning
In machine learning, "imbalanced classes" is a familiar problem particularly occurring in classification when we have datasets with an unequal ratio of data points in each class. Training of model becomes much trickier as typical accuracy is no longer a reliable metric for measuring the performance of the model. Now if the number of data points in
15 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read