Abstraction in Python (with Examples)

Abstraction is one of the fundamental principles of object-oriented programming (OOP). It helps in hiding the complexity of a system by exposing only the essential fields (or details). It allows to focus on “what” a class or method does without needing to worry about “how” it does it.

In Python, abstraction is achieved using abstract classes and methods, which are part of the ABC (Abstract Base Classes) module.

Abstraction in Python

Abstraction in Object Oriented Programming (OOP) refers to hiding the internal implementation of a method or a class, allowing the user to interact with the system at a high level. In simpler terms, it helps in simplifying complex systems by providing a clean interface for the user to interact with.

For example, when we use a TV remote control, we don’t need to know the internal mechanics of how the remote sends signals to the TV. We just press a button to get a specific result. This is a practical example of abstraction in daily life.

Uses of Abstraction

Abstraction is useful because it allows us to:

  • Hide complex logic and details.
  • Simplify the interaction between different parts of a system.
  • Encourage code reuse and modularity.
  • Make systems easier to understand and maintain.

By abstracting certain details, developers can focus on high-level functionality while ignoring low-level details.

Abstract Classes in Python

In Python, an abstract class is a class that cannot be instantiated directly (cannot create an object directly of abstract class). It is designed to be subclassed, providing a blueprint for other classes. An abstract class typically contains one or more abstract methods that must be implemented by any subclass.

To create an abstract class, we need to import ABC (Abstract Base Class) and abstractmethod from the abc module.

# import ABC (Abstract Base Class) and abstractmethod from the abc module
from abc import ABC, abstractmethod

# abstract class
class Shbytes(ABC):
	def instituteName(self):
		print("shbytes")

	@abstractmethod             # annotation used on abstract method
	def trainingCourse(self):   # abstract method
		print("TrainingCourse@shbytes")
  • In this example, Shbytes is an abstract class with two methods – instituteName() is the normal method and trainingCourse() method is an abstract method annotated with @abstractmethod.
  • Any class inherits from Shbytes class must implement the abstract method.

Abstract Methods in Python

An abstract method is a method that is declared in the abstract class and annotated with @abstractmethod. Abstract methods should be overridden in the subclasses, ensuring that every subclass provides its own version of the method.

Practical example of abstraction in Python

# import ABC (Abstract Base Class) and abstractmethod from the abc module
from abc import ABC, abstractmethod

# abstract class with ABC as parent class
class Shbytes(ABC):
	def instituteName(self):
		print("shbytes")
	
	@abstractmethod
	def trainingCourse(self):            # abstract method
		print("TrainingCourse@shbytes")

class PowerBITraining(Shbytes):          # class inherits from Shbytes class
	# overriding abstract method
	def trainingCourse(self):            # define trainingCourse() abstract method from parent class
		print("Training Course - Power BI")

class PythonTraining(Shbytes):           # class inherits from Shbytes class
	# overriding abstract method
	def trainingCourse(self):            # define trainingCourse() abstract method from parent class
		print("Training Course - Python")
 
class MLTraining(Shbytes):               # class inherits from Shbytes class
	# overriding abstract method
	def trainingCourse(self):            # define trainingCourse() abstract method from parent class
		print("Training Course - ML")

Here, the Shbytes abstract class defines an abstract method trainingCourse(), which will be implemented by various other classes like PowerBITraining, PythonTraining and MLTraining.

Now, if we create instances of these subclasses and call the trainingCourse() method, we get different results based on the subclass method implementation.

powerbi_training = PowerBITraining()  # create an object and instance of PowerBITraining class
powerbi_training.trainingCourse()     # call trainingCourse() method from PowerBITraining class
powerbi_training.instituteName()      # call instituteName() method from parent Shbytes abstract class

python_training = PythonTraining()  # create an object and instance of PythonTraining class
python_training.trainingCourse()    # call trainingCourse() method from PythonTraining class
python_training.instituteName()     # call instituteName() method from parent Shbytes abstract class

ml_training = MLTraining()      # create an object and instance of MLTraining class
ml_training.trainingCourse()    # call trainingCourse() method from MLTraining class
ml_training.instituteName()     # call instituteName() method from parent Shbytes abstract class

# object of an abstract class cannot be created
print("object of an abstract class cannot be created")
try:
	training1 = Shbytes()   # Will give error - cannot create an object of abstract class
except TypeError as err:
	print("error", err)

Program Output

Training Course - Power BI
shbytes

Training Course - Python
shbytes

Training Course - ML
shbytes

object of an abstract class cannot be created
error Can't instantiate abstract class Shbytes without an implementation for abstract method 'trainingCourse'

Summary

In this article, we learned about Abstraction in Python. Following concepts were covered:

  • Abstraction allows you to focus on “what” a method does, rather than “how” it works.
  • Abstract classes are used to define common interfaces for a group of related classes.
  • Abstract methods are methods that must be implemented by subclasses.
  • Python provides the abc module to support abstraction.

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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