Python for Polyglots
Lesson 8 · Core

Classes & dataclasses

Python has no new, no access modifiers, and an explicit self. @dataclass removes the boilerplate.

  • __init__ is the constructor. Every method takes self (Java's this) explicitly as its first parameter.
  • Nothing is truly private. A leading _name means "internal" by convention only.
  • Dunder methods (named with double underscores) plug into the language: __str__ works like toString(), __eq__ like equals(), and __len__ makes len(x) work and makes empty objects falsy.
  • @property lets you read a method like a field. It's an alternative to getters.
  • No interfaces. Python uses duck typing: if an object has the right methods, it works. For type checking, typing.Protocol behaves like a structural TypeScript interface.
  • @dataclass generates __init__, __repr__ and __eq__ for you. It's the closest thing to a Java record.
A small value class
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: float
    y: float

    def norm(self) -> float:
        return (self.x ** 2 + self.y ** 2) ** 0.5

p = Point(3, 4)
print(p, p.norm(), p == Point(3, 4))
A regular class with dunders and a property
class Account:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance      # "private" by convention

    @property
    def balance(self):               # read it like a field: acct.balance
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("amount must be positive")
        self._balance += amount
        return self                  # allows chaining

    def __repr__(self):
        return f"Account({self.owner!r}, {self._balance})"

    def __eq__(self, other):
        return isinstance(other, Account) and self.owner == other.owner

acct = Account("ana").deposit(50).deposit(25)
print(acct, acct.balance)
print(acct == Account("ana"))
Quiz: What does this print?
class P:
    def __init__(self, x):
        self.x = x

print(P(1) == P(1))
Exercise 22: A Point dataclass

Replace the class with a @dataclass Point that has fields x and y, plus a method distance_to(other) that returns the straight-line distance.

Point(0, 0).distance_to(Point(3, 4)) → 5.0. Points must compare by value and be usable in a set.

Exercise 23: A Stack class

Build a last-in-first-out stack backed by a list. pop() and peek() on an empty stack must raise IndexError. len(s) must work, and an empty stack must be falsy.