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 takesself(Java'sthis) explicitly as its first parameter.- Nothing is truly private. A leading
_namemeans "internal" by convention only. - Dunder methods (named with double underscores) plug into the language:
__str__works liketoString(),__eq__likeequals(), and__len__makeslen(x)work and makes empty objects falsy. @propertylets 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.Protocolbehaves like a structural TypeScript interface. @dataclassgenerates__init__,__repr__and__eq__for you. It's the closest thing to a Javarecord.
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.