Python Abstract Classes

We know that a class is a model for creating objects (or instances). A class contains properties and actions. Attributes are nothing but variables and actions are represented by methods.

When objects are created to a class, the objects also get the variables and actions mentioned in the class. The rule is that anything that is written in the class is applicable to all of its objects.If a method is written in the class, it is available to all the class objects.

Python Abstract Class Example

#A class with a method 
class Myclass: 
   def calculate(self, x): 
      print('Square value=', x*x) 
obj1 = Myclass() 
obj2 = Myclass() 
obj3 = Myclass() 

For example, in the preceding program, if the first object wants to calculate square value, the second object wants the square root value and the third object wants cube value.

When each object wants one method, providing all the three does not look reasonable. To serve each object with the one and only required method, we can follow the steps:

  1. First, let's write a calculate() method in Myclass. This means every object wants to calculate something.
  2. If we write body for calculate() method, it is commonly available to all the objects. So let's not write body for calculate() method. Such a method is called abstract method. Since, we write abstract method in Myclass, it is called abstract class.
  3. Now derive a sub class Sub1 from Myclass, so that the calculate() method is available to the sub class. Provide body for calculate() method in Sub1 such that it calculates square value. Similarly, we create another sub class Sub2 where we write the calculate() method with body to calculate square root value. We create the third sub class Sub3 where we write the calculate() method to calculate cube value. This hierarchy is shown in Figure.
  4. It is possible to create objects for the sub classes. Using these objects, the respective methods can be called and used. Thus, every object will have its requirement fulfilled.
Python Abstract Class