Skip to main content

Mastering `__init__` in Python

OOP Core

The __init__ Method

`__init__` sets up each instance. Validate inputs, wire dependencies, and keep state consistent.

Signatures

class Invoice:
def __init__(self, *, total: float, customer: str, currency: str = "USD"):
if total < 0:
raise ValueError("Total must be positive")
self.total = total
self.customer = customer
self.currency = currency
  • Use keyword-only parameters for clarity.
  • Avoid heavy business logic; keep initialization focused.

Calling super()

class PriorityInvoice(Invoice):
def __init__(self, *, priority_level: int, **kwargs):
super().__init__(**kwargs)
self.priority_level = priority_level
  • Always call super().__init__ when inheriting to ensure base initialization runs.

Next up in your learning path