DEV Community

Cover image for Abstract Base Class (ABC)
Carlos Almonte
Carlos Almonte

Posted on

Abstract Base Class (ABC)

You can force other classes to implement a certain method. If you wanted the cute puppy to inherit from the cute dog class you can tell the cute dog class to inherit from ABC, and this will allow you to make use of the @abstractmethod decorator which will force cute puppy to implement the abstract method. Otherwise, if the method is not implemented the code will throw an error.

from abc import ABC, abstractmethod

class CuteDog(ABC):

  @abstractmethod
  def bark(self):
    pass

class CutePuppy(CuteDog):
  # no bark method, throws an error
Enter fullscreen mode Exit fullscreen mode
from abc import ABC, abstractmethod

class CuteDog(ABC):

  @abstractmethod
  def bark(self):
    pass

class CutePuppy(CuteDog):
  # this works
  def bark(self):
    print("woof!")
Enter fullscreen mode Exit fullscreen mode

Top comments (0)