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.
To hide implementation details and show only essential features
Abstraction focuses on exposing only necessary features while hiding complex implementation details.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
pass
obj = Dog()
TypeError at instantiation
Python raises a `TypeError` when you try to instantiate a subclass that doesn't implement all abstract methods.
Marks a method as requiring implementation in subclasses
The `@abstractmethod` decorator enforces that concrete subclasses must implement the decorated method.
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.
It will raise a TypeError
Python will raise a `TypeError` if you attempt to instantiate an abstract class that has unimplemented abstract methods.
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
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).
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.
`abc`
The `abc` module provides the `ABC` metaclass and `@abstractmethod` decorator for creating abstract classes.
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.
abc
The `abc` module in Python provides infrastructure for defining Abstract Base Classes.
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())
50.24
Since the `Circle` class implements the abstract method `area`, it can be instantiated and will return the calculated area.
To enforce certain methods in subclasses
Abstract base classes are used to define a common interface and enforce that derived classes implement specific methods.
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()
`Default connection logic` followed by `MySQL connection`
Abstract methods CAN have implementations in Python. The subclass invokes the parent's implementation via `super()`.
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)
Abstract classes can have both abstract and concrete methods
The `receipt()` method is fully implemented in the abstract class and shared by all subclasses.
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])
All of the above
This demonstrates encapsulation (validation hiding), method enforcement (`export()`), and reusable shared logic (`validate()`).
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())
16
Since `Square` properly implements the abstract `area()` method, it can be instantiated, and the calculation works correctly.
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
Missing `close()` implementation in `FileLogger`
Subclasses must implement ALL abstract methods. Here, `close()` is missing.
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!")
Violates Liskov Substitution Principle (Bicycle isn't a valid Vehicle)
Forcing `Bicycle` to implement engine methods indicates a flawed abstraction hierarchy.
A. Hiding unnecessary details and showing only essential features B. Combining variables C. Using loops D. Creating objects
Answer: A (GeeksforGeeks)
A. math B. sys C. abc D. os
Answer: C
A. A class with no methods B. A class that cannot be instantiated directly C. A normal class D. A private class
Answer: B (GeeksforGeeks)
A. @staticmethod B. @classmethod C. @abstractmethod D. @property
Answer: C
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def area(self):
return 100
obj = Circle()
print(obj.area())
A. Error B. 0 C. 100 D. None
Answer: C
A. Faster execution B. Simplicity by hiding complexity C. More memory usage D. Redundant code
Answer: B (GeeksforGeeks)
A. Shows internal logic B. Hides implementation details C. Removes methods D. Only works with loops
Answer: B
A. Runs successfully B. Gives warning C. Raises error D. Returns None
Answer: C
A. Writing code B. ATM machine interface C. Variable declaration D. Loop execution
Answer: B
A. Both are same B. Encapsulation hides data, abstraction hides implementation C. Encapsulation shows details D. Abstraction exposes everything
Answer: B (Boot.dev)
class Shape(ABC):
def area(self):
pass
What is missing?
A. from abc import ABC
B. import math
C. import sys
D. Nothing
Answer: A
from abc import ABC
class Shape(ABC):
def area(self):
pass
What is the correction?
A. Add @abstractmethod
B. Remove class
C. Add constructor
D. Use static method
Answer: A
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
pass
obj = Circle()
What is the fix?
A. Implement area() in Circle
B. Remove ABC
C. Add constructor
D. Use private method
Answer: A
from abc import ABC, abstractmethod
class A(ABC):
@abstract
def show(self):
pass
What is the correction?
A. Replace @abstract with @abstractmethod
B. Remove decorator
C. Add constructor
D. Use @staticmethod
Answer: A
from abc import ABC, abstractmethod
class Test(ABC):
@abstractmethod
def show(self):
pass
obj = Test()
What is the fix?
A. Create subclass and implement method B. Remove ABC C. Add variable D. Use static method
Answer: A
class A:
def __init__(self):
self.__x = 10
class B(A):
def show(self):
print(self.__x)
What is the fix?
A. Use self._A__x
B. Make variable global
C. Remove class
D. Use static method
Answer: A
from abc import ABC, abstractmethod
class Bank(ABC):
def __init__(self):
self.__balance = 100
@abstractmethod
def get_balance(self):
pass
class ATM(Bank):
pass
obj = ATM()
What is the fix?
A. Implement get_balance() in ATM
B. Remove constructor
C. Make variable public
D. Delete abstract method
Answer: A