Learn with Yasir

Share Your Feedback

Python abstraction MCQs – Test Your OOP Knowledge


Challenge your understanding of Python's Object-Oriented Programming with these multiple-choice questions on abstraction. Ideal for beginners, students, and job seekers to reinforce key OOP concepts.

📝 Multiple Choice Questions

🟢 Beginner

Q1. What is the primary purpose of abstraction in OOP?

  • 🟢 A. To hide implementation details and show only essential features
  • 🔵 B. To allow multiple inheritance in Python
  • 🟠 C. To enforce strict type checking
  • 🔴 D. To optimize code performance
Answer

To hide implementation details and show only essential features

Abstraction focuses on exposing only necessary features while hiding complex implementation details.


Q2. What will happen if a subclass doesn't implement an abstract method?

from abc import ABC, abstractmethod
class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    pass
obj = Dog()
  • 🟢 A. The code will run without errors
  • 🔵 B. TypeError at class definition
  • 🟠 C. TypeError at instantiation
  • 🔴 D. The method will inherit the parent's implementation
Answer

TypeError at instantiation

Python raises a `TypeError` when you try to instantiate a subclass that doesn't implement all abstract methods.


Q3. What does the `@abstractmethod` decorator do?

  • 🟢 A. Prevents a method from being called
  • 🔵 B. Marks a method as requiring implementation in subclasses
  • 🟠 C. Makes a method private
  • 🔴 D. Optimizes method execution speed
Answer

Marks a method as requiring implementation in subclasses

The `@abstractmethod` decorator enforces that concrete subclasses must implement the decorated method.


Q4. What is abstraction in object-oriented programming?

  • 🟢 A. Hiding the internal implementation and showing only the necessary features
  • 🔵 B. Creating private variables
  • 🟠 C. Restricting access using access modifiers
  • 🔴 D. Writing multiple methods with the same name
Answer

Hiding the internal implementation and showing only the necessary features

Abstraction is the concept of hiding complex implementation details and showing only the essential features to the user.


Q5. What will happen if you try to instantiate an abstract class with an unimplemented abstract method?

  • 🟢 A. It will raise a TypeError
  • 🔵 B. It will return None
  • 🟠 C. It will call the method with default implementation
  • 🔴 D. It will execute without any error
Answer

It will raise a TypeError

Python will raise a `TypeError` if you attempt to instantiate an abstract class that has unimplemented abstract methods.


Q6. What is the purpose of `ABC.register()` here?

from abc import ABC
class Duck:
    def quack(self):
        print("Quack!")

class Bird(ABC):
    @classmethod
    def __subclasshook__(cls, subclass):
        return hasattr(subclass, 'quack')

Bird.register(Duck)
duck = Duck()
print(isinstance(duck, Bird))  # Output: True
  • 🟢 A. Ensures `Duck` implements all abstract methods of `Bird`
  • 🔵 B. Dynamically registers `Duck` as a virtual subclass of `Bird`
  • 🟠 C. Prevents `Duck` from being instantiated
  • 🔴 D. Creates a strict inheritance relationship
Answer

Dynamically registers `Duck` as a virtual subclass of `Bird`

`register()` allows non-inheriting classes to be treated as subclasses if they meet the interface (duck typing).


🟡 Intermediate

Q1. How is abstraction typically achieved in Python?

  • 🟢 A. Using private methods with `__` prefix
  • 🔵 B. Using abstract base classes (ABC) and `@abstractmethod`
  • 🟠 C. Through function decorators only
  • 🔴 D. By overloading operators
Answer

Using abstract base classes (ABC) and `@abstractmethod`

Python uses the `abc` module and `@abstractmethod` decorator to enforce abstraction by requiring subclasses to implement specific methods.


Q2. Which module is required to create abstract classes in Python?

  • 🟢 A. `abstract`
  • 🔵 B. `abc`
  • 🟠 C. `oop`
  • 🔴 D. `abstractmethod` only (no module needed)
Answer

`abc`

The `abc` module provides the `ABC` metaclass and `@abstractmethod` decorator for creating abstract classes.


Q3. Which of the following is TRUE about abstraction in Python?

  • 🟢 A. Abstract methods can have implementations in the parent class
  • 🔵 B. A class with at least one abstract method can be instantiated
  • 🟠 C. Abstract classes must inherit from `object`
  • 🔴 D. Abstract methods can be declared without the `abc` module
Answer

Abstract methods can have implementations in the parent class

Abstract methods in Python can have implementations, but subclasses must still override them. The `@abstractmethod` decorator marks them as requiring override.


Q4. Which module in Python provides the base class for creating abstract classes?

  • 🟢 A. abc
  • 🔵 B. abstract
  • 🟠 C. base
  • 🔴 D. oop
Answer

abc

The `abc` module in Python provides infrastructure for defining Abstract Base Classes.


Q5. What is the output of 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 * 4 * 4

c = Circle()
print(c.area())
  • 🟢 A. 50.24
  • 🔵 B. Error: Can't instantiate abstract class
  • 🟠 C. None
  • 🔴 D. 8
Answer

50.24

Since the `Circle` class implements the abstract method `area`, it can be instantiated and will return the calculated area.


Q6. Why do we use abstract base classes in Python?

  • 🟢 A. To enforce certain methods in subclasses
  • 🔵 B. To allow direct instantiation
  • 🟠 C. To reduce memory usage
  • 🔴 D. To avoid using constructors
Answer

To enforce certain methods in subclasses

Abstract base classes are used to define a common interface and enforce that derived classes implement specific methods.


Q7. What is the output of this code?

from abc import ABC, abstractmethod
class Database(ABC):
    @abstractmethod
    def connect(self):
        print("Default connection logic")

class MySQL(Database):
    def connect(self):
        super().connect()
        print("MySQL connection")

db = MySQL()
db.connect()
  • 🟢 A. `MySQL connection`
  • 🔵 B. `Default connection logic` followed by `MySQL connection`
  • 🟠 C. TypeError (cannot instantiate abstract class)
  • 🔴 D. Error: `super()` misuse
Answer

`Default connection logic` followed by `MySQL connection`

Abstract methods CAN have implementations in Python. The subclass invokes the parent's implementation via `super()`.


Q8. What does this code demonstrate about abstraction?

from abc import ABC, abstractmethod
class PaymentGateway(ABC):
    @abstractmethod
    def process_payment(self, amount):
        pass

    def receipt(self, amount):
        print(f"Receipt for ${amount}")

class PayPal(PaymentGateway):
    def process_payment(self, amount):
        print(f"Processing ${amount} via PayPal")

payment = PayPal()
payment.process_payment(100)
payment.receipt(100)
  • 🟢 A. Abstract classes can have both abstract and concrete methods
  • 🔵 B. `receipt()` must also be abstract
  • 🟠 C. Subclasses cannot use parent's concrete methods
  • 🔴 D. Abstract methods must return a value
Answer

Abstract classes can have both abstract and concrete methods

The `receipt()` method is fully implemented in the abstract class and shared by all subclasses.


Q9. What makes this code a proper abstraction?

from abc import ABC, abstractmethod
class DataExporter(ABC):
    @abstractmethod
    def export(self, data):
        pass

    def validate(self, data):
        return isinstance(data, list)

class CSVExporter(DataExporter):
    def export(self, data):
        if self.validate(data):
            print(f"Exporting {len(data)} rows to CSV")
        else:
            raise ValueError("Invalid data format")

exporter = CSVExporter()
exporter.export([1, 2, 3])
  • 🟢 A. It hides validation logic inside the abstract class
  • 🔵 B. It forces subclasses to implement `export()` but shares `validate()`
  • 🟠 C. It uses `ABC` to prevent instantiation
  • 🔴 D. All of the above
Answer

All of the above

This demonstrates encapsulation (validation hiding), method enforcement (`export()`), and reusable shared logic (`validate()`).


🔴 Advanced

Q1. What is the output of the following code?

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side ** 2

s = Square(4)
print(s.area())
  • 🟢 A. 0
  • 🔵 B. 16
  • 🟠 C. TypeError (Shape cannot be instantiated)
  • 🔴 D. Error (Square doesn't implement `area()`)
Answer

16

Since `Square` properly implements the abstract `area()` method, it can be instantiated, and the calculation works correctly.


Q2. Why does this code fail?

from abc import ABC, abstractmethod
class Logger(ABC):
    @abstractmethod
    def log(self, message):
        pass

    @abstractmethod
    def close(self):
        pass

class FileLogger(Logger):
    def log(self, message):
        print(f"Log: {message}")

logger = FileLogger()  # Error occurs here
  • 🟢 A. Missing `close()` implementation in `FileLogger`
  • 🔵 B. Abstract methods cannot have parameters like `message`
  • 🟠 C. `FileLogger` must inherit from `object` first
  • 🔴 D. `@abstractmethod` cannot be used twice
Answer

Missing `close()` implementation in `FileLogger`

Subclasses must implement ALL abstract methods. Here, `close()` is missing.


Q3. What is the key problem in this design?

from abc import ABC, abstractmethod
class Vehicle(ABC):
    @abstractmethod
    def start_engine(self):
        pass

    @abstractmethod
    def stop_engine(self):
        pass

class Bicycle(Vehicle):
    def start_engine(self):
        raise NotImplementedError("Bicycles have no engine!")

    def stop_engine(self):
        raise NotImplementedError("Bicycles have no engine!")
  • 🟢 A. Violates Liskov Substitution Principle (Bicycle isn't a valid Vehicle)
  • 🔵 B. `NotImplementedError` should be replaced with `pass`
  • 🟠 C. Abstract methods cannot raise exceptions
  • 🔴 D. Missing `@abstractmethod` decorator in `Bicycle`
Answer

Violates Liskov Substitution Principle (Bicycle isn't a valid Vehicle)

Forcing `Bicycle` to implement engine methods indicates a flawed abstraction hierarchy.