Abstract Class (with example)

Abstract Class (With Example)

Abstract Class in Python: 


  A class which contain (at least) one or more abstract method  in its definition is called as abstract class .Abstract class is a class which can not be instantiated  which means we cannot create object of that class, such class can only be inherited and object of that subclass can access the features of an abstract class.

 An abstract class corresponds to abstract concept .For example shape may refers to a square, 
circle, rectangle hence , an abstract class is  a class that is specifically defines to lay a foundation for other classes that exhibits common behavior or similar characteristics .so basically abstract class
is a template for other subclasses. 

NOTE

creating an object of an abstract class causes an error .


Abstract Class is one of the important feature of OOP .we can create an abstract class using 
abstract keyword in other programming languages like java and c++.but Python on its own does not allow to create an abstract class directly , to create an abstract class  in python we have to import an inbuilt module " abc " 


Syntax : 

from abc import ABC ,abstractmethod:

or

from abc import *           # " * "import everything under" abc  "

from the " abc "  module we have to import two things  ABC and abstractmethod where ABCs stand for "Abstract Base class " . 




Example : 
 Program to understand concept of abstract class

from abc import ABC,abstractmethod

class shape(ABC):

   @abstractmethod

   def area (self):

       pass

   @abstractmethod

   def info(self):

       pass

class square(shape):

    def area (self,side):

        self.side=side

        print(side*side)

   def info(self,side):

       print("Number of sides in square are",side)


Square = square()

Square.area(5)

Square.info(5)



Output :


25

Number of sides in square are 5




Abstract Class



To make a class as an abstract we have inherited it from ABC as we did in the above program .
an abstract class must have abstract methods that methods we have to define in a subclass again .

 So basically abstract class is an incomplete class ,and users are not allow to create an object of it. therefore , we see that an abstract class just serve as a template for other classes .It make no sense to create an object of an abstract class because all methods in it are empty and must be defined in its subclass.


Meta class in Python :  

   A meta class is the class of class. while a class defines how an instance of the class behaves ,a meta class on other hand defines how class behaves ,so every class that we defined in Python is instance i.e.
object of meta class . A meta class is commonly used as a class factory . 





NOTE

In python, a new class is created by calling the meta class.