Ticker

6/recent/ticker-posts

OOPS (Object-Oriented Programming Language) Part-3

 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.
The given Python code uses the ​ABC​ class and defines an abstract base class:

Note: 

  • 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. 
For example, ​We will now define a subclass using the previously defined abstract class. You will notice that since we haven't implemented the ​do_something method, in this subclass, we will get an exception.




We will get out as:






























Post a Comment

1 Comments