×

Python Abstract Class

An Introduction to Abstract Classes

An Abstract Class is one of the most significant concepts of Object-Oriented Programming (OOP). An Abstract class can be deliberated as a blueprint or design for other classes. It is a sound practice of the Don't Repeat Yourself (DRY) principle as duplicating codes in a large project is approximately similar to reusing bugs. A developer can't remember all details of the classes. Thus, the use of an abstract class becomes efficient while defining a common interface for distinct implementations. It also allows the developers to design a set of methods created necessarily within any subclasses constructed from the abstract class.

When a class contains one or more abstract methods is known as Abstract Class. The abstract methods are the methods that only have declarations but do not have any detailed implementation.

Some features of an Abstract class are as follows:

  • We cannot instantiate an abstract class. It only helps as an interface for child classes to avoid any code duplication. It does not make any sense to instantiate an abstract class.
  • We can implement the abstract methods using a derived child class to create a concrete class that fits the abstract class's interface. Thus, we cannot instantiate it until and unless all of its abstract methods get overridden.

In short, we can also say that an abstract class is used to define a common interface for a set of child classes or subclasses. It delivers common properties and methods for all child classes to reduce duplication of code. It also helps in enforcing the child classes to implement an abstract method avoiding odd contradictions.

What is the need for Abstract Base Classes?

We can define a common API (Application Program Interface) for a set of child classes by defining an Abstract Base Class. This Abstract Base Class capability becomes specifically useful in conditions where a third-party provides implementations like in the case of plugins. However, it can also help us while working in a big team or with a large codebase where it is difficult to remember all the classes.

Working of Abstract Base Classes

Python does not provide Abstract Classes by default. However, it does come with a module providing the base to define Abstract Base Classes (abbreviated as ABC). This Python module is known as ABC. The ABC module works by adorning base class methods as abstract and then registering concrete classes as abstract base implementations. We can create a method abstract by decorating using the keyword, namely @abstractmethod.

Let us consider the following example to understand the working of an Abstract Base Class.

Example:

from abc import ABC, abstractmethod 
 class Shapes(ABC): 
     # defining abstract method 
     def sides(self): 
         pass
 class Circle(Shapes): 
     # overriding an abstract method 
     def sides(self): 
         print("Circle has ONE curved side.") 
 class Triangle(Shapes):
     # overriding an abstract method 
     def sides(self): 
         print("Triangle has THREE sides.") 
 class Square(Shapes):
     # overriding an abstract method 
     def sides(self): 
         print("Square has FOUR sides.") 
 class Pentagon(Shapes):
     # overriding an abstract method 
     def sides(self): 
         print("Pentagon has FIVE sides.") 
 shape_1 = Circle()
 shape_1.sides()
 shape_2 = Triangle()
 shape_2.sides()
 shape_1 = Square()
 shape_1.sides()
 shape_2 = Pentagon()
 shape_2.sides() 

Output:

 Circle has ONE curved side.
 Triangle has THREE sides.
 Square has FOUR sides.
 Pentagon has FIVE sides. 

Explanation –

In the above example, we have imported the ABC module and defined a class called Shapes. We have then defined an abstract method called sides. Later, we have defined some subclasses such as Circle, Triangle, Square, and Pentagon that inherit the attributes and methods of the superclass Shapes and override the abstract method. At last, we have created some objects and print the output to the user.

Using Subclassing for Abstract Class Implementation

The need for explicitly registering the class can be avoided by subclassing from the base directly. In such cases, the Python class management helps in recognizing PluginImplementation with the abstract PluginBase implementation.

Let us look at the following example to understand the concept of implementing abstract class via subclassing.

Example:

import abc 
 class superClass:    
     def myMethod(self):
         pass
 class subClass(superClass): 
     def myMethod(self):
         print("This a Subclass.") 
 print( issubclass(subClass, superClass)) 
 print( isinstance(subClass(), superClass)) 

Output:

 True
 True 

In the above example, we have imported the abc module. We have defined two classes: the first one is the superClass, where the other is its subClass and defined an abstract method. Finally, we have used two functions, namely issubclass() and isinstance(), respectively.

The issubclass() function allows the user to check if the first argument is a child class of the second argument. The isinstance() function allows the user to check if the object (i.e., first argument) is an instance or the second argument's child class.

However, there are some side-effects of utilizing direct subclassing. We can find all the user's plugin implementations just by asking the parent class for the list of acknowledged classes inherited from it.

Concrete Methods in Abstract Base Classes

Concrete Classes consist of only normal (concrete) methods, whereas the abstract classes may consist of the abstract methods as well as the concrete methods. The concrete class delivers an implementation of the abstract methods, whereas the abstract base class can also deliver an implementation by invoking the methods using the super() function.

Let us consider the following example illustrating the functioning of the super() function in invoking a method.

Example:

import abc 
 from abc import ABC, abstractmethod 
 class myClass(ABC): 
     def myMethod(self): 
         print("Abstract Base Class") 
 class mySubClass(myClass): 
     def myMethod(self):
         super().myMethod() 
         print("Child Class") 
 first_class = mySubClass() 
 first_class.myMethod() 

Output:

 Abstract Base Class
 Child Class 

Explanation –

In the above example, we have imported the abc module and defined a superclass, named myClass. We have then defined a method, named myMethod() for myClass. Later, we have defined another class, named mySubClass, that inherits the attributes and methods from myClass. We have also used the super() function to invoke the methods in abstract classes. Finally, we have created an object called first_class of mySubClass to print the Output to the user.

Understanding Abstract Properties

Abstract Classes involve methods as well as attributes. The attributes can be required in the concrete classes by defining them with the keyword known as @abstractproperty.

Let us consider the following example illustrating abstract properties.

Example:

import abc 
 from abc import ABC, abstractmethod 
 class parent_class(ABC): 
     @abc.abstractproperty 
     def myMethod(self): 
         return "The Superclass"
 class child_class(parent_class):
     @property
     def myMethod(self): 
         return "The Subclass"
 try: 
     first = parent_class() 
     print( first.myMethod())
 except Exception as err:
     print (err)
 first = child_class() 
 print( first.myMethod) 

Output:

 Can't instantiate abstract class parent_class with abstract method myMethod
 The Subclass 

Explanation –

In the above snippet of code, we have imported the abc module. We have defined two classes: the parent_class class as a base class and the child_class class that inherits the base class's methods and attributes.

We have used the return with a try/except statement to return some statements. At last, we have inserted an object, namely first and print the output.

Moreover, in the output, it is visible that the Parent class cannot be instantiated. The program returned this error because of having only an abstract version of the property getter method.

Instantiating an Abstract Class

Abstract Classes are incomplete as they contain methods with nobody. Suppose Python provides access to create an object for abstract classes then utilizing it if anyone calls the abstract method. However, there are no such actual implementations for invoking. Thus, we utilize an abstract class like a template, and we extend it as per the requirement and build on it before utilization. Hence, an abstract class is not a concrete class, and we cannot instantiate them. It will return an error while creating an object for an abstract class.

Let us look at the following example, illustrating that we cannot instantiate an abstract class.

Example:

from abc import ABC, abstractmethod 
 class Cars(ABC):
     @abstractmethod
     def intro(self): 
         pass
 class BMW(Cars): 
     def intro(self): 
         print("This is a BMW car.") 
 class Volkswagen(Cars):
     def intro(self): 
         print("This is a Volkswagen car.") 
 class Ford(Cars):
     def intro(self): 
         print("This is a Ford truck.") 
 class Jaguar(Cars):
     def intro(self): 
         print("This is a Jaguar car.") 
 car = Cars() 

Output:

 Traceback (most recent call last):
   File "D:\Python\abstract.py", line 23, in <module>
     car = Cars()
 TypeError: Can't instantiate abstract class Cars with abstract method intro 

Related Topics

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.