Lesson

Python Classes and Objects

10 min reading
Free Course

Python Classes and Objects: Modeling State and Behavior

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.

Defining a Class with __init__ and self

Python 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)

Cleaner Data Models with @dataclass

When 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

Common Mistakes to Avoid

  • Forgetting self in method definitions: Python passes the instance automatically as the first argument, so omitting self causes TypeError.
  • Sharing mutable class attributes: Putting items = [] on the class body shares one list across all instances; initialize mutable fields inside __init__.
  • Missing __repr__: Without __repr__ (or @dataclass), printing an object displays an unhelpful memory address.

Frequently Asked Questions

Why must 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.

Can I attach new attributes to an object after creation?

Yes, though defining every expected attribute inside __init__ keeps your code predictable for teammates and type checkers.

When should I use @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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Python Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum