2. Use Abstract Classes To Define Common Interfaces

Sumit Rawal answered on May 13, 2023 Popularity 9/10 Helpfulness 1/10

Contents


More Related Answers


2. Use Abstract Classes To Define Common Interfaces

0
Tip Sumit Rawal 1 GREPCC

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: 

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.

Popularity 9/10 Helpfulness 1/10 Language python
Source: Grepper
Tags: python
Link to this answer
Share Copy Link
Contributed on May 13 2023
Sumit Rawal
0 Answers  Avg Quality 2/10


X

Sign in with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
X
Grepper Account Login Required

Oops, You will need to install Grepper and log-in to perform this action.