Example for Abstraction in Python [2 Examples]

Here’s an example of abstraction in Python:

from abc import ABC, abstractmethod

class Vehicle(ABC):
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    @abstractmethod
    def start_engine(self):
        pass

    @abstractmethod
    def stop_engine(self):
        pass

class Car(Vehicle):
    def start_engine(self):
        print(f"The {self.brand} {self.model}'s engine is started.")

    def stop_engine(self):
        print(f"The {self.brand} {self.model}'s engine is stopped.")

class Motorcycle(Vehicle):
    def start_engine(self):
        print(f"The {self.brand} {self.model}'s engine is started.")

    def stop_engine(self):
        print(f"The {self.brand} {self.model}'s engine is stopped.")

# Create instances of different vehicles
car = Car("Toyota", "Camry")
motorcycle = Motorcycle("Harley-Davidson", "Sportster")

# Start and stop the engines without knowing the internal details
car.start_engine()       # Output: The Toyota Camry's engine is started.
car.stop_engine()        # Output: The Toyota Camry's engine is stopped.
motorcycle.start_engine()  # Output: The Harley-Davidson Sportster's engine is started.
motorcycle.stop_engine()   # Output: The Harley-Davidson Sportster's engine is stopped.
Code language: Python (python)

In this example, we have an abstract base class Vehicle that represents a generic vehicle. It has two abstract methods, start_engine() and stop_engine(), which define the behavior of starting and stopping the engine.

The Car and Motorcycle classes inherit from Vehicle and provide their own implementations of the start_engine() and stop_engine() methods. Each class implements these methods differently based on the specific behavior of their respective vehicle types.

By creating instances of Car and Motorcycle and calling the start_engine() and stop_engine() methods, we can work with vehicles at a higher level of abstraction. The underlying implementation details are hidden, and we can interact with the vehicles using the common interface provided by the Vehicle class.

Example 2

Here’s another example of abstraction in Python:

from abc import ABC, abstractmethod

class Database(ABC):
    @abstractmethod
    def connect(self):
        pass

    @abstractmethod
    def execute_query(self, query):
        pass

class MySQLDatabase(Database):
    def connect(self):
        print("Connecting to MySQL database...")

    def execute_query(self, query):
        print(f"Executing query '{query}' in MySQL database.")

class PostgreSQLDatabase(Database):
    def connect(self):
        print("Connecting to PostgreSQL database...")

    def execute_query(self, query):
        print(f"Executing query '{query}' in PostgreSQL database.")

# Create instances of different databases
mysql_db = MySQLDatabase()
postgresql_db = PostgreSQLDatabase()

# Connect to databases and execute queries without knowing the internal details
mysql_db.connect()  # Output: Connecting to MySQL database...
mysql_db.execute_query("SELECT * FROM users")  # Output: Executing query 'SELECT * FROM users' in MySQL database.

postgresql_db.connect()  # Output: Connecting to PostgreSQL database...
postgresql_db.execute_query("SELECT * FROM customers")  # Output: Executing query 'SELECT * FROM customers' in PostgreSQL database.
Code language: Python (python)

In this example, we have an abstract base class Database that defines the interface for connecting to a database and executing queries. It has two abstract methods, connect() and execute_query(), which need to be implemented by any concrete subclass.

The MySQLDatabase and PostgreSQLDatabase classes inherit from Database and provide their own implementations of the connect() and execute_query() methods. Each class implements these methods differently based on the specific behavior of connecting to and interacting with their respective database types.

By creating instances of MySQLDatabase and PostgreSQLDatabase and calling the connect() and execute_query() methods, we can work with databases at a higher level of abstraction. We don’t need to know the specific details of how each database is connected to or how queries are executed, but we can still perform these operations using the common interface provided by the Database class.

Read More;

  • Yaryna Ostapchuk

    I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

    View all posts

Leave a Comment