Abstract Base Classes in Python (abc)


A class is called an Abstract class if it contains one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.

Abstract base classes provide a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass() functions. There are many built-in ABCs in Python. ABCs for Data structures like Iterator, Generator, Set, mapping etc. are defined in collections.abc module. The numbers module defines numeric tower which is a collection of base classes for numeric data types. The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes.

'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator. A concrete class which is a sub class of such abstract base class then implements the abstract base by overriding its abstract methods.

The abc module defines ABCMeta class which is a metaclass for defining abstract base class. Following example defines Shape class as an abstract base class using ABCMeta. The shape class has area() method decorated by abstractmethod.

A Rectangle class now uses above Shape class as its parent and implementing the abstract area() method. Since it is a concrete class, it can be instantiated and imlemented area() method can be called.

import abc
class Shape(metaclass=abc.ABCMeta):
   @abc.abstractmethod
   def area(self):
      pass
class Rectangle(Shape):
   def __init__(self, x,y):
      self.l = x
      self.b=y
   def area(self):
      return self.l*self.b
r = Rectangle(10,20)
print ('area: ',r.area())

Note the abstract base class may have more than one abstract methods. The child class must implement all of them failing which TypeError will be raised.

the abc module also defines ABC helper class which can be used instead of ABCMeta class in definition of abstract base class.

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

Instead of subclassing from abstract base class, it can be registered as abstract base by register class decorator.

class Shape(abc.ABC):
   @abc.abstractmethod
   def area(self):
      pass
@Shape.register
class Rectangle():
   def __init__(self, x,y):
   self.l = x
   self.b=y
   def area(self):
      return self.l*self.b

You may also provide class methods and static methods in abstract base class by decorators @abstractclassmethod and @abstractstatic method decorators respectively.

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements