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.