Explore programming tutorials, exercises, quizzes, and solutions!
Python Abstraction Exercises
1/20
In Python, abstraction is an object-oriented programming principle that allows you to define essential behavior without providing full implementation details. It helps developers focus on what an object does rather than how it does it.
Python supports abstraction using the abc (Abstract Base Classes) module. You can define abstract classes and enforce method implementation in derived classes using the @abstractmethod decorator. This is particularly useful when building large systems where common interfaces must be followed but each class may implement its own specific logic.
Consider the following code:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def area(self):
return 3.14 * 5 * 5
circle = Circle()
print(circle.area())
What concept does this code illustrate about abstraction in Python?
This example uses the abc module to define an abstract base class (Shape). It contains an abstract method area() that has no implementation — it uses pass.
By decorating area() with @abstractmethod, Python ensures that any class inheriting from Shape must implement area().
If the Circle class didn’t implement area(), creating an instance like Circle() would raise a TypeError.
This allows you to define a consistent interface across multiple subclasses (Rectangle, Triangle, etc.) without knowing how each shape calculates its area.
Abstraction helps you build flexible and scalable systems where each component adheres to a defined structure, while still allowing individual customization.
Which Python module provides support for creating abstract base classes?
The abc module in Python is used to define Abstract Base Classes. It allows developers to create classes that cannot be instantiated directly and enforce certain methods to be implemented by child classes.
What will be the output of the following code?
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
This code defines an abstract class using the ABC module with an abstract method area(). This class cannot be instantiated directly but can be subclassed, and subclasses are expected to provide an implementation for area().
Which of the following statements is true about abstract classes in Python?
An abstract class in Python must contain at least one abstract method (a method declared but not implemented). Such classes cannot be instantiated and are typically used as blueprints for other classes.
Why can't you instantiate an abstract class in Python?
Abstract classes may contain one or more abstract methods that are not implemented. Python prevents instantiation of such classes to ensure that those methods are implemented by subclasses first.
What will happen if we try to instantiate an abstract class without providing implementation for its abstract method?
If you try to instantiate an abstract class that contains an abstract method without implementing that method, Python will raise a TypeError. This ensures that all abstract methods are implemented before instantiating the class.
Consider the following code. What will be the output?
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Bark"
d = Dog()
print(d.sound())
In this code, Dog inherits from Animal and implements the abstract method sound(). When we create an instance of Dog and call sound(), it successfully prints "Bark", as expected.
What is the purpose of the @abstractmethod decorator in Python?
The @abstractmethod decorator marks a method in an abstract class as needing implementation in subclasses. Any class that inherits from this abstract class must provide an implementation for the method, otherwise, a TypeError will be raised.
Which of the following is true about abstract methods in Python?
Abstract methods in abstract classes do not have a body in the base class. They are meant to be overridden in subclasses, though the implementation can be empty or just a pass statement.
What will be the output of the following code?
from abc import ABC, abstractmethod
class Computer(ABC):
@abstractmethod
def boot(self):
pass
class Laptop(Computer):
def boot(self):
return "Laptop booting up"
class Desktop(Computer):
pass
l = Laptop()
d = Desktop()
print(l.boot())
print(d.boot())
The class Laptop implements the boot() method, so calling l.boot() prints "Laptop booting up". However, the class Desktop does not implement boot(), and thus attempting to create an instance of Desktop will raise a TypeError because it has an unimplemented abstract method.
What will be the output of the following code?
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
circle = Circle(5)
rectangle = Rectangle(4, 6)
print(circle.area())
print(rectangle.area())
Both the Circle and Rectangle classes inherit from Shape and need to implement the area() method. However, since area() is not implemented in either of these classes, trying to instantiate them will raise a TypeError.
In the following code, why will it raise a TypeError?
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def process_payment(self, amount):
pass
class CreditCardPayment(Payment):
pass
payment = CreditCardPayment()
payment.process_payment(100)
The CreditCardPayment class inherits from Payment but does not implement the abstract method process_payment(). Since the abstract method is not implemented, Python raises a TypeError when attempting to instantiate CreditCardPayment.
Given the following code, what will be the output?
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
t = Triangle(5, 10)
print(t.area())
The class Triangle correctly implements the area() method from the abstract class Shape. When the instance t is created and area() is called, it correctly calculates the area of the triangle (0.5 * 5 * 10 = 50.0).
What will happen if the following code is executed?
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
return "Car started"
class Bike(Vehicle):
pass
car = Car()
bike = Bike()
print(car.start())
print(bike.start())
The Car class implements the start() method, so calling car.start() works fine. However, the Bike class does not implement the start() method and raises a TypeError when trying to instantiate it.
What will be the result of the following code?
from abc import ABC, abstractmethod
class Computer(ABC):
@abstractmethod
def display(self):
pass
class Laptop(Computer):
def display(self):
return "Laptop Display"
class Desktop(Computer):
def display(self):
return "Desktop Display"
def get_computer_type(comp):
return comp.display()
laptop = Laptop()
desktop = Desktop()
print(get_computer_type(laptop))
print(get_computer_type(desktop))
Both Laptop and Desktop implement the abstract method display(). The function get_computer_type(comp) calls the display() method for each computer type, resulting in "Laptop Display" and "Desktop Display".
What will be the output of the following code?
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
shapes = [Circle(5), Square(4), Rectangle(4, 6)]
for shape in shapes:
print(f"Area of {shape.__class__.__name__}: {shape.area()}")
The code defines three different shapes (Circle, Square, and Rectangle), each with a defined area() method. The program iterates over a list of shape objects and calls their respective area() methods, printing the calculated area for each shape.
What will be the output of this code?
from abc import ABC, abstractmethod
class DataStorage(ABC):
@abstractmethod
def store_data(self, data):
pass
class CloudStorage(DataStorage):
def store_data(self, data):
return f"Data stored in the cloud: {data}"
class LocalStorage(DataStorage):
def store_data(self, data):
return f"Data stored locally: {data}"
def save(storage, data):
return storage.store_data(data)
cloud = CloudStorage()
local = LocalStorage()
print(save(cloud, "Document"))
print(save(local, "Image"))
Both CloudStorage and LocalStorage implement the store_data() method. The function save() accepts a storage object and a data string, then calls store_data() on the provided object. The output will show the respective data storage locations.
What will be the output of this code?
from abc import ABC, abstractmethod
class Account(ABC):
@abstractmethod
def account_type(self):
pass
class CheckingAccount(Account):
def account_type(self):
return "Checking Account"
class SavingsAccount(Account):
def account_type(self):
return "Savings Account"
def print_account_type(account):
return account.account_type()
checking = CheckingAccount()
savings = SavingsAccount()
print(print_account_type(checking))
print(print_account_type(savings))
Both CheckingAccount and SavingsAccount classes implement the account_type() method. The function print_account_type(account) calls the account_type() method on the passed account instance, outputting the correct account type.
What will happen if the following code is executed?
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
return "Car started"
class Bike(Vehicle):
pass
car = Car()
bike = Bike()
print(car.start())
print(bike.start())
The Car class implements the start() method, so calling car.start() works fine. However, the Bike class does not implement the start() method, and thus trying to instantiate it will raise a TypeError.
What will be the result of the following code?
from abc import ABC, abstractmethod
class Computer(ABC):
@abstractmethod
def display(self):
pass
class Laptop(Computer):
def display(self):
return "Laptop Display"
class Desktop(Computer):
def display(self):
return "Desktop Display"
def get_computer_type(comp):
return comp.display()
laptop = Laptop()
desktop = Desktop()
print(get_computer_type(laptop))
print(get_computer_type(desktop))
Both Laptop and Desktop implement the abstract method display(). The function get_computer_type(comp) calls the display() method for each computer type, resulting in "Laptop Display" and "Desktop Display".
Practicing Python Abstraction? Don’t forget to test yourself later in
our
Python Quiz.
About This Exercise: Python – Abstraction
Welcome to the Python Abstraction exercises — a carefully crafted set of challenges aimed at helping you understand and apply one of the key concepts of object-oriented programming. Abstraction focuses on hiding the complex implementation details of a class while exposing only the essential features and behaviors. This makes your code simpler, cleaner, and easier to maintain. Whether you are new to OOP or want to deepen your Python skills, these exercises will guide you through the fundamentals and practical uses of abstraction.
In Python, abstraction is often implemented using abstract base classes and methods, which you can define using the abc module. These abstract classes act as blueprints for other classes, requiring them to implement specific methods while hiding the underlying details. You will practice creating abstract classes, defining abstract methods, and understanding how subclasses provide concrete implementations.
These exercises also emphasize the importance of designing interfaces that separate what a class does from how it does it. This separation allows developers to work more effectively, improving modularity and reducing dependencies between components. You’ll explore real-world examples where abstraction simplifies complex systems, such as designing APIs, software frameworks, or large-scale applications.
Mastering abstraction is essential for writing scalable, maintainable Python applications that can evolve without breaking existing code. It’s a foundational skill for professional software development, enabling you to build flexible systems that are easier to test, extend, and debug. Additionally, understanding abstraction prepares you for technical interviews where OOP design questions often focus on these concepts.
Along with hands-on coding exercises, this section highlights best practices such as designing clear and minimal interfaces, avoiding unnecessary exposure of internal details, and combining abstraction with other OOP principles like encapsulation and inheritance. These strategies help you write clean, efficient Python code.
To reinforce your learning, consider exploring related topics such as classes and objects, inheritance, and polymorphism. You can also benefit from quizzes and multiple-choice questions available on our platform to test your understanding of abstraction concepts.
Start practicing the Python Abstraction exercises today to gain confidence in building robust, flexible Python programs. With regular practice, you’ll be able to design elegant software architectures that stand the test of time.