Abstract Classes and Methods in Python

  • Abstract classes are classes that contain one or more abstract methods.
  • An abstract method is a method that is declared, but have no implementation of code.
  • Abstract classes cannot be instantiated, and require subclasses to provide implementations for the abstract methods.
  • Python comes with a module called abc to implement Abstract Base Classes (ABCs).
  • @abstractmethod is used to declare method as a abstract method inside the abstract class.
from abc import ABC, abstractmethod

class Car(ABC):
    @abstractmethod
    def color(self):
        pass
    def display(self):
        print("Hello from Abstract class display method")

myAbsObj = Car()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-65ca296d7e22> in <module>
----> 1 myAbsObj = Car()

TypeError: Can't instantiate abstract class Car with abstract methods color


myAbsObj.color()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-6198f43df24f> in <module>
----> 1 myAbsObj.color()

NameError: name 'myAbsObj' is not defined


myAbsObj.display()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-df6155992d55> in <module>
----> 1 myAbsObj.display()

NameError: name 'myAbsObj' is not defined
class HondaCar(Car):
    def color(self):
        super.color()
        print("White Color Honda Car")

myHondaCar = HondaCar()
myHondaCar.color()
White Color Honda Car

References:

  • https://docs.python.org/3/library/abc.html
  • https://docs.python.org/3/glossary.html#term-abstract-base-class

Learn more about Python Features in the upcoming blog articles.

Happy Learning!