Lesson 5 of 7 · Classes and Objects · 3 min read · Updated
Abstraction and abstract classes
Describing what every kind of object must do, while leaving how it does it to each one.
Abstraction means working with what something does and hiding how. You call print() without knowing how it reaches the screen. In classes, an abstract class writes the promise down: every subclass must provide these methods.
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount):
...
def receipt(self, amount):
return f"Paid ₹{amount} by {self.pay(amount)}"
class UPI(Payment):
def pay(self, amount):
return "UPI"
class Card(Payment):
def pay(self, amount):
return "card"
for method in [UPI(), Card()]:
print(method.receipt(500))
try:
Payment()
except TypeError:
print("Cannot create a Payment directly")
Paid ₹500 by UPI
Paid ₹500 by card
Cannot create a Payment directly
- Inheriting from
ABC(from the standardabcmodule) makes Payment abstract. @abstractmethodmarkspayas required. The...body is a placeholder that is never run.- An abstract class cannot be created itself — only its complete subclasses can.
- Ordinary methods such as
receiptare shared, and can rely onpayexisting.
from abc import ABC, abstractmethod
class Payment(ABC):
@abstractmethod
def pay(self, amount):
...
class Cash(Payment):
pass
try:
Cash()
except TypeError:
print("Cash must define pay() first")
Cash must define pay() first
Note
Compare the NotImplementedError approach in the Polymorphism lesson: it fails only when the missing method is called, perhaps weeks later. An abstract class fails the moment an incomplete object is created, which is far easier to track down.
A class inherits from an abstract class but does not define one of its abstract methods. What happens?
Try this now
- Write an abstract
Shapewith abstractarea()andperimeter(), thenCircleandSquaresubclasses. - Add a
describe()method to Shape that uses both abstract methods, and call it on each subclass.
Create a free account to save your progress, or sign in.