Python abstractions

Python Abstraction

Abstraction is a key principle of object-oriented programming. It refers to a programming approach that exposes only relevant data about an object, hiding all other details. This approach helps reduce complexity and improve application development efficiency.

There are two types of abstraction. One is data abstraction, which hides the original data entity by hiding its data structure. The other type is called procedural abstraction, which hides the underlying implementation details of the procedure.

In object-oriented programming terminology, if a class cannot be instantiated, it is called an abstract class. In other words, you can have an object of an abstract class. However, you can use it as a base class or parent class for building other classes.

To create an abstract class in Python, it must extend the ABC class defined in the abc module. This module is available in Python’s standard library. In addition, the class must have at least one abstract method. Again, an abstract method is a method that cannot be called but can be overridden. You need to decorate it with the @abstractmethod decorator.

Example

from abc import ABC, abstractmethod
class demo(ABC):
@abstractmethod
def method1(self):
print ("abstract method")
return
def method2(self):
print ("concrete method")

The demo class inherits the ABC class. It has one method, method1(), which is an abstract method. Note that the class may have other non-abstract (concrete) methods.

If you try to declare an object of the demo class, Python will raise a TypeError −

obj = demo()
^^^^^^
TypeError: Can't instantiate abstract class demo with abstract method method1

The demo class here can be used as a parent class of another class. However, the child class must override the abstract method in the parent class. Otherwise, Python throws the following error:

TypeError: Can't instantiate abstract class concreteclass with abstract method method1

Therefore, the following example shows a subclass instantiation that overrides an abstract method.

from abc import ABC, abstractmethod
class democlass(ABC):
@abstractmethod
def method1(self):
print ("abstract method")
return
def method2(self):
print ("concrete method")

class concreteclass(democlass):
def method1(self):
super().method1()
return

obj = concreteclass()
obj.method1()
obj.method2()

Output

When you execute this code, it will produce the following output –

abstract method
concrete method

Leave a Reply

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