Python Object-Oriented Programming
Fundamentals Deep Dive
Python OOP
Once you master functions, step up to Python's class system. Learn how to design classes, leverage dataclasses, and compose behavior with inheritance and mixins.
Classes and instances
class Invoice:
def __init__(self, total: float, customer: str):
self.total = total
self.customer = customer
def apply_discount(self, percent: float) -> None:
self.total *= 1 - percent
invoice = Invoice(100, "Microsoft")
invoice.apply_discount(0.1)
Encapsulation
- Use leading underscore
_balanceto signal "internal use." - Provide methods/properties for controlled access.
class Account:
def __init__(self, balance: float = 0):
self._balance = balance
@property
def balance(self) -> float:
return self._balance
Inheritance & mixins
class Notification:
def send(self, message: str) -> None:
raise NotImplementedError
class EmailNotification(Notification):
def send(self, message: str) -> None:
...
Use inheritance for "is-a" relationships. Use mixins (small classes providing shared behavior) to avoid deep hierarchies.
Dataclasses
from dataclasses import dataclass
@dataclass
class Course:
id: str
title: str
active: bool = True
- Auto-generates
__init__,__repr__,__eq__. - Set
frozen=Truefor immutability.
Magic methods
Implement dunder methods to customize behavior:
| Method | Purpose |
|---|---|
__repr__ / __str__ | String representations |
__len__ | Length (len(obj)) |
__iter__ | Iterator support |
__enter__ / __exit__ | Context manager support |
Next up in your learning path
Frequently Asked Questions
Should I always use classes?
No. Start with functions and simple data types. Reach for classes when you need to bundle state + behavior, enforce invariants, or model complex domains.
How do dataclasses compare to namedtuples?
Dataclasses are mutable by default and easier to extend. Namedtuples are immutable and lightweight. Choose based on mutability requirements.
What about slots?
Using `__slots__` can reduce memory usage by preventing dynamic attribute creation, but it removes flexibility. Evaluate case by case.