Abstract Classes in Python

 

An abstract class is a class that generally contains some abstract methods. Abstract method is a method whose implementation is defined later in the sub classes.

Once an abstract class is written, we should create subclasses and all the abstract methods should be implemented in the sub classes.

The way to create an abstract class is to derive it from a meta class ABC that belongs to the module abc(abstract base class)

import abc

class Abstractclassname(ABC):

      @abstract methods

Program

 from abc import ABC
class Mathevent(ABC):#abstract class because it is inherited from ABC meta class
    def area(self,x,y): #concrete method which has implementation details
        print("area of a rectangle:",x*y)
    def calculate(self,x): #abstract method which does not have implementation
        pass
class square(Mathevent):
    def calculate(self,x):
        print("square value is:",x*x)
class cube(Mathevent):
    def calculate(self,x):
        print("cube value is:",x*x*x)
s=square()
s.area(13,12)
c=cube()
c.calculate(10)

Output:-

area of a rectangle: 156
cube value is: 1000


 

Comments

Popular posts from this blog

Strings in Python

Tuples in Python

Exception Handling in Python