Overview of Abstract Class in Python
An Abstract Class is a class that cannot be implemented on its own, and entails subclasses for the purpose of employing the abstract class to access the abstract methods. Here comes the concept of inheritance for the abstract class for creating the object from the base class. In Python, the Abstract classes comprises of their individual abstract properties with respect to the abstract method of the respective class, which is defined by the keyword ‘@abstractproperty’.
Both the abstract class as well as the concrete class can be contained in the Abstract class. By using an abstract class we can define a generalized structure of the methods without providing complete implementations of every method. Abstract methods that are defined in the abstract class generally don’t have the body, but it is possible to have abstract methods with implementations in the abstract class and if any subclass is getting derived from such abstract class needs to provide the implementation for such methods. If any abstract method is not implemented by the derived class then it will throw an error. The abstract class object can’t be directly created, but when we use this abstract class to provide certain functionalities to a base class or child class it can do that by creating the object of the base class.
Importance of Abstract Classes
1. It provides the default functionality of the base classes.
2. It defines a common API for the set of subclasses, useful where a third party is providing plugins in an application.
3. Helpful in large code was remembering many classes is difficult.
From abc import ABC Class Educba(ABC):
To consider any class as an abstract class, the class has to inherit ABC metaclass from the python built-in abc module. abc module imports the ABC metaclass.
Abstract Methods in Python
Abstract methods are the methods that are declared without any implementations.
from abc import ABC, abstractmethod Class Educba(ABC): @abstractmethod def mymethod(self): #empty body pass
To define the abstract methods in an abstract class, the method must be decorated with a keyword called @abstractmethod decorator. The @abstractmethod decorator has to be imported from the python built-in library called abc.
How did Abstract Classes work in Python?
Python does not have abstract classes by default, but it has a module or library which forms the base for defining Abstract Base classes (ABC) and that module name is called ABC. It marks the method of the base class as the abstract base class and then produces concrete classes as implementations of the abstract base. A method turns into an abstract method with the help of a decorator keyword called @abstractmethod.
ABC module is used to create the abstract classes,@abstractmethod is the decorator used to declare the method abstract. ABC module establishes a contract between the base class and the concrete class.
The abc module provides the basis for defining abstract base classes (ABC) in Python. The collections module has some concrete classes that are derived from ABC and they can be further divided. Apart from all these, the collections module also contains some ABC that can be used to test whether a class or instance provides a particular interface or not.
This module provides the following class:
The metaclass is used for defining Abstract Base Classes (ABC)
We use a metaclass to create an abstract base class.
from abc import ABCMeta class C: __metaclass__ = ABCMeta MyABC.register(tuple) assert issubclass(tuple, C) assert isinstance((), C)
# importing the ABC module from abc import ABC, abstractmethod class Shape(ABC): def common(self): print("This is a concrete method") @abstractmethod # decorator def area(self): pass @abstractmethod def perimeter(self): pass class Square(Shape): def __init__(self,side): self.__side=side def area(self): return self.__side*self.__side def perimeter(self): return 4*self.__side class Rectangle(Shape): def __init__(self,length,breath): self.__length=length class Rectangle(Shape): def __init__(self,length,breath): self.__length=length self.__breath=breath def area(self): return self.__length*self.__breath def perimeter(self): return 2*(self.__length+self.__breath) S1=Square(4) print(S1.common()) print(S1.area()) print(S1.perimeter()) R1=Rectangle(2,4) print(R1.common()) print(R1.area()) print(R1.perimeter())
This is a concrete method
This is a concrete method
In the above example, the Abstract class is Shape which contains one concrete method called common and two abstract methods called area and perimeter. There are two child Classes Square and Rectangle that inherit the abstract class Shape and implement the abstract method.
Implementation through Subclassing:
import abc class Shape: def area(self): pass class Square(Shape): def area(self): print("Square is a child class") print( issubclass(Square,Shape)) print( isinstance(Square(), Shape))
Abstract classes contain abstract properties along with abstract methods defined by @abstractproperty.
We can now use property,property.getter(),property.setter() and property.deleter() with abstract classes.
cclass class_name(ABC): @property @abstractmethod Def method(self):
This defines the read-only property.
class Class_name: __metaclass__ = ABCMeta def getx(self): ... def setx(self, value): ... x = abstractproperty(getx, setx)
class C(ABC): @property @abstractmethod def my_abstract_property(self):
import abc from abc import ABC, abstractmethod class Shape(ABC): @abc.abstractproperty def area(self): return "Shape class" class Square(parent): @property def area(self): return "Square class" try: s1 =Shape() print( s1.area) except Exception as err: print (err) s1 = Square() print (s1.area)
Can’t instantiate abstract class Shape with abstract method area
At last, I conclude that abstract class is a way to ensure a certain level of code quality because they enforce certain standards and can reduce the amount of duplicate code that we write. It establishes a connection between the base class and the concrete class. It provides an easy implementation of code. It defines a generalized structure of methods without its complete implementation. It makes the life of the programmer easy by abstracting the background process and making them focus only on important points. It makes the research and understandability much quicker by understanding the common and simple structure of classes within the code.
This is a guide to Abstract Class in Python. Here we discuss the basic concept, how do Abstract Classes work in Python with the importance and methods with appropriate examples. You may also have a look at the following articles to learn more –