A Python class is a blueprint for creating objects that bundle data (attributes) and behavior (methods) together. Each object created from that blueprint is an instance with its own independent state.
Classes keep related logic organized when plain dictionaries and loose functions become hard to track across a growing project.
__init__ and selfPython calls __init__() automatically whenever you instantiate a class. The self parameter refers to the specific object being created or accessed.
class BankAccount:
currency = "USD" # Class attribute shared across instances
def __init__(self, owner: str, balance: float = 0.0) -> None:
self.owner = owner # Instance attribute
self.balance = balance
def deposit(self, amount: float) -> float:
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
acct = BankAccount("Rohan", 100.0)
print(acct.deposit(50.0), acct.currency)
@dataclassWhen a class mostly holds data fields, Python's @dataclass decorator generates __init__, __repr__, and __eq__ automatically:
from dataclasses import dataclass
@dataclass
class Product:
sku: str
price: float
in_stock: bool = True
self in method definitions: Python passes the instance automatically as the first argument, so omitting self causes TypeError.items = [] on the class body shares one list across all instances; initialize mutable fields inside __init__.__repr__: Without __repr__ (or @dataclass), printing an object displays an unhelpful memory address.self be written explicitly in Python methods?Python follows the rule "explicit is better than implicit." Passing self makes it clear whether a method reads instance state or module globals.
Yes, though defining every expected attribute inside __init__ keeps your code predictable for teammates and type checkers.
@dataclass instead of a regular class?Use @dataclass for structured records and DTOs; write a plain class when you need custom __init__ validation or complex inheritance.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.