An abstract class, which is an important concept of OOP, can define a common interface for a set of subclasses. It provides common attributes and methods for all subclasses to reduce code duplication. It also enforces subclasses to implement abstract methods to avoid inconsistencies.
Python, like other OOP languages, supports the usage of abstract classes.
The following example shows how to define a class as an abstract class by abc.ABC and define a method as an abstract method by abc.abstractmethod:
xxxxxxxxxx
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
print('Animal moves')
class Cat(Animal):
def move(self):
super().move()
print('Cat moves')
c = Cat()
c.move()
# Animal moves
# Cat moves
This example defines an abstract class called Animal, and a class Cat which is inherited from Animal.
Given that the Animal is an abstract class and its move() method is an abstract method, we must implement the move() method in the Cat class. This mechanism helps to ensure that all subclasses have a certain set of methods, and helps to prevent errors that might occur if the subclasses do not implement all of the required methods.
The ABC, by the way, is the abbreviation of abstract base class.