Updated April 17, 2023
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.
Syntax
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.
Syntax
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:
class abc.ABCMeta
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)
Example
# 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())
Output:
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 Properties
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.
Syntax
class 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)
Python 2
class C(ABC):
@property
@abstractmethod
def my_abstract_property(self):
Python 3.3
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)
Output:
Can’t instantiate abstract class Shape with abstract method area
Square class
Conclusion
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.
Recommended Articles
We hope that this EDUCBA information on “Abstract Class in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.