Intermediate LevelPython
How do you enforce interface contracts on child classes using the abc module and @abstractmethod?
❓ Interview Prompt: Explain Abstract Base Classes (`ABC`), `@abstractmethod`, enforcing interface contracts, and `TypeError` on incomplete instantiation.
The 'abc' module provides Abstract Base Classes (ABCs) to define explicit interface contracts for child subclasses:
Enforcing Interfaces:
•
Subclass 'ABC' and decorate required methods with '@abstractmethod'.
•
Attempting to instantiate a subclass that fails to implement all abstract methods raises a 'TypeError' at runtime!
Code Implementation Example
python
from abc import ABC, abstractmethod
class PaymentGateway(ABC):
@abstractmethod
def process_payment(self, amount: float) -> bool:
pass
class StripeGateway(PaymentGateway):
def process_payment(self, amount: float) -> bool:
print(f'Processing ${amount} via Stripe')
return True
# PaymentGateway() # TypeError: Can't instantiate abstract class!💡Enforcing interface contracts using ABC and @abstractmethod.
🎯 Interview Key Takeaway
Use ABCs and @abstractmethod to define and enforce explicit object-oriented interface contracts.
#ABC#Abstract Base Class#@abstractmethod#Intermediate
Back to all Python Questions→