stackademic

The leading education platform for anyone with an interest in software development.

Classes

Define objects with attributes, methods, inheritance, and dunder methods

Overview

Classes bundle data (attributes) and behavior (methods). Python supports single inheritance, multiple inheritance, and duck typing. The self parameter refers to the instance and must be the first parameter of instance methods.

Syntax / Usage

class User:
    def __init__(self, name: str, email: str):
        self.name = name
        self.email = email
        self._active = True

    def deactivate(self):
        self._active = False

    @property
    def active(self) -> bool:
        return self._active

    def __repr__(self):
        return f"User(name={self.name!r})"

class Admin(User):
    def __init__(self, name, email, level: int):
        super().__init__(name, email)
        self.level = level

Examples

Model a bank account with validation:

class Account:
    def __init__(self, owner: str, balance: float = 0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount: float):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.balance += amount

    def withdraw(self, amount: float):
        if amount > self.balance:
            raise ValueError("Insufficient funds")
        self.balance -= amount

Use @dataclass for simple data containers:

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

Common Mistakes

  • Forgetting self in method definitions and calls
  • Putting mutable class attributes shared across instances
  • Overusing inheritance when composition is simpler
  • Not implementing __repr__, making debugging harder

See Also

python-functions python-decorators python-exceptions