In this tutorial, you will learn how to create a class that uses the abstract base class with ABC in Python to define a class. Python 2 has a module called abc (abstract base class) that offers the necessary tools for creating an abstract base class. Most importantly, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass.
Python Program: Declaring an Abstract Base Class
An abstract base class provides a common set of functionality to all classes that descend from it. It’s a superclass that doesn’t have any instance data. It provides a default implementation of some operations (like the constructor) and defines what properties are available for subclasses. An abstract base class can be used for several purposes. One is to define a behavior pattern. Another is to give a template class. A third reason to create an abstract base class is to hide details in the base class from subclasses.
from abc import ABCMeta, abstractmethod #class Base(metaclass = ABCMet): class Base(): metaclass = ABCMeta @abstractmethod def foo(self): pass @abstractmethod def bar(self): pass class Real(Base): def foo(self): print('foo in Real') def bar(self): print('bar in Real') def other(self): pass class Fake(Base): def foo(self): print('foo in Fake') r = Real() f = Fake() # TypeError: Can't instantiate abstract class Fake with abstract methods bar