Pre-defined functions are similar to data abstraction.
For example, when you use a washing machine for laundry purposes. What you do is you put your laundry and detergent inside the machine and wait for the machine to perform its task. How does it perform it? What mechanism does it use? A user is not required to know the engineering behind its work. This process is typically known as data abstraction, when all the unnecessary information is kept hidden from the users.
In Python, we can achieve abstraction by incorporating abstract classes and methods.
Any class that contains abstract method(s)
is called an abstract class. Abstract methods do not include any implementations – they are always defined and implemented as part of the methods of the sub-classes inherited from the abstract class. Look at the sample syntax below for an abstract class:
from abc import ABC
// abc is a library from where a class ABC is being imported. However, a separate class can also be created. The importing from the library has nothing to do with abstraction.
Class type_shape(ABC):
The class type_shape
is inherited from the ABC
class. Let’s define an abstract method area
inside the class
type_shape
:
from abc import ABC
class type_shape(ABC):
// abstract method area
def area(self):
pass
The implementation of an abstract class is done in the sub-classes, which will inherit the class type_shape
. We have defined four classes that inherit the abstract class type_shape
in the code below:
from abc import ABCclass type_shape(ABC):def area(self):#abstract methodpassclass Rectangle(type_shape):length = 6breadth = 4def area(self):return self.length * self.breadthclass Circle(type_shape):radius = 7def area(self):return 3.14 * self.radius * self.radiusclass Square(type_shape):length = 4def area(self):return self.length*self.lengthclass triangle:length = 5width = 4def area(self):return 0.5 * self.length * self.widthr = Rectangle() # object created for the class 'Rectangle'c = Circle() # object created for the class 'Circle's = Square() # object created for the class 'Square't = triangle() # object created for the class 'triangle'print("Area of a rectangle:", r.area()) # call to 'area' method defined inside the class.print("Area of a circle:", c.area()) # call to 'area' method defined inside the class.print("Area of a square:", s.area()) # call to 'area' method defined inside the class.print("Area of a triangle:", t.area()) # call to 'area' method defined inside the class.