Abstraction in Python

In this tutorial ,we will be learning more about the concept of abstraction in a clear manner. Usually abstraction concept is mainly used to hide the complex implementation details and allows access only to the essential information which is useful for the user. In python, abstraction can be achieved by using abstract classes and interfaces. If a class contain one or more abstract method we can define that class as abstract class. We can have the access to use complex implementations or objects in python without needing to understand the details.

Example for abstraction in python

class Jeep:
def start(self):
#method that will help to start the jeep
print("The jeep has started.")
def stop(self):
#method that will help you stop the jeep
print("The jeep has stopped.")
def accelerate(self):
#method that will help you to accelerate the jeep
print("The jeep is accelerating.")
def brake(self):
#method that will help you to brake the jeep
print("The brakes stopped the jeep.")
my_jeep=Jeep()
my_jeep.start()
my_jeep.stop()
my_jeep.accelerate()
my_jeep.brake()

The code which we have provided above helps to understand the concept of abstraction. We represent the actions of the jeep with the help of methods like start, stop, accelerate, brake. We have provided the print statement to indicate the action being performed.
Let me explain how the above code regarding to the abstraction works:

  • Initially we have created the class by initializing class instance name by giving the name as jeep. It helps for creating objects, encapsulating methods and data that operate on the object.
  • Each method call the result in the corresponding message being printed to the console.
Output:
The jeep has started
The jeep has stopped
The jeep is accelerating
The brakes stopped the jeep

Leave a Comment

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

Scroll to Top