Abstract Class Python

Abstract Class and Method in Python

In Python you can create an abstract class using library, but by default   there are not any mechanisms to provide abstract classes.

A class is called abstract if it has abstract methods, an abstract method has not any definition , definition should be implemented by the child class which inherits it. See the example below

from abc import ABC, abstractmethod
class Quadrilateral(ABC):
    @abstractmethod
    def  perimeter(self):
        pass
    
class Rectangle(Quadrilateral):
    def __init__(self, x,y):
        self.x=x
        self.y=y
    def  perimeter(self):
        pr=2 * (self.x + self.y)
        return pr
class Square(Quadrilateral):
    def __init__(self, x):
        self.x=x
    def  perimeter(self):
        ps=4*(self.x )
        return ps
r=Rectangle(10,15)
prm=r.perimeter()
print(prm)
s=Square(10)
prm=s.perimeter()
print(prm)

In the above program,  an abstract class Quadrilateral  is defined which contains only one method perimeter () which is abstract.  The abstract method perimeter() is implemented by child classes Square and Rectangle.

Furthermore, instance of an abstract class can not be created

i.e. if you try to create an instance of  Quadrilateral class interpreter will through an error.

q=Quadrilateral()

The following error program will encounter

TypeError: Can’t instantiate abstract class Quadrilateral with abstract methods perimeter

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.