2.4.1 Abstraction
Abstraction (Python OOP)
Abstraction means: show only what is necessary, hide the complicated parts.
In real life:
- When you use an ATM, you see buttons like Withdraw and Check Balance.
- You do not see how the bank database works internally.
In programming:
- You design classes so other people (or future-you) can use them easily.
- The user of a class calls a few clear methods and doesn’t need to know the internal details.
Why Abstraction Matters
- Simpler code to use: fewer things to think about.
- Fewer mistakes: users can’t accidentally use internal steps in the wrong order.
- Easier changes: you can improve the internal implementation without changing how others use it.
Example 1: A Simple EmailSender Interface
Imagine you want to send an email. The caller shouldn’t need to know about SMTP details.
PYTHON
class EmailSender:
def __init__(self, smtp_host):
self.smtp_host = smtp_host
def send(self, to, subject, body):
self._connect()
self._authenticate()
self._send_message(to, subject, body)
self._disconnect()
def _connect(self):
print(f"Connecting to {self.smtp_host}...")
def _authenticate(self):
print("Authenticating...")
def _send_message(self, to, subject, body):
print(f"Sending to={to} subject={subject} body={body}")
def _disconnect(self):
print("Disconnected")
sender = EmailSender("smtp.example.com")
sender.send("user@example.com", "Hello", "Welcome!")
What’s abstract here?
- The public method is
send(). - The internal steps are hidden behind “private-like” methods:
_connect(),_authenticate(), etc.
Example 2: Abstraction with an Abstract Base Class (ABC)
Sometimes you want a common interface for different implementations.
Example: You want to support multiple payment methods, but your app code should call them the same way.
PYTHON
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
pass
class CardPayment(PaymentMethod):
def pay(self, amount):
return f"Paid {amount} using card"
class CashPayment(PaymentMethod):
def pay(self, amount):
return f"Paid {amount} using cash"
def checkout(payment_method, amount):
print(payment_method.pay(amount))
checkout(CardPayment(), 500)
checkout(CashPayment(), 500)
Abstraction here means:
- Your app relies on the method name and signature:
pay(amount). - Each payment type can implement details however it wants.
Common Beginner Confusions
-
Abstraction vs Encapsulation
- Abstraction is about designing a simple interface.
- Encapsulation is about protecting/hiding data and controlling access.
-
Underscore methods are not “truly private” in Python
_method()is a convention: “this is internal, please don’t call it directly.”
Quick Practice
Build a class called MusicPlayer with:
- a public method
play(song_name) - internal methods like
_load_song()and_start_audio_device()
Goal: code that uses your class should only need to call play().