Object-Oriented Programming-3
Abstract Classes
An abstract class can be considered as a blueprint for other classes. Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that has a declaration but does not have an implementation. This set of methods must be created within any child classes which inherit from the abstract class. A class that contains one or more abstract methods is called an abstract class.
Creating Abstract Classes in Python
- By default, Python does not provide abstract classes.
- Python comes with a module that provides the base for defining Abstract Base classes(ABC) and that module name is abc.
- abc works by decorating methods of the base class as abstract and then registering concrete classes as implementations of the abstract base.
- A method becomes abstract when decorated with the keyword @abstractmethod.
- You are required to import ABC superclass and abtractmethod from the abc module before declaring your abstract class.
- An abstract class cannot be directly instantiated i.e. we cannot create an object of the abstract class.
- While declaring abstract methods in the class, it is not mandatory to use the @abstractmethod decorator (i.e it would not throw an exception). However, it is considered a good practice to use it as it notifies the compiler that the user has defined an abstract method.
- You are required to define (implement) all the abstract methods declared in an Abstract class, in all its subclasses to be able to instantiate the subclass.
We will get out as:
1 Comments
Thanks for the content
ReplyDelete