Classes, properties and dataclasses
When data comes with rules (a balance that may never go negative, an id that must not change), a plain dict cannot enforce them. A class can. This lesson shows how a class keeps data and its rules together, the tools for validated and read-only fields, and dataclasses for simple record types.
Foundations · Python for data engineers · Silver · Classes and robust code, lesson 1 of 2
On this page
Read first: Mutability, copies and default arguments (skip if you know it)
In plain words first
A bank account is not just a number. You cannot simply write a new balance into it; you deposit or withdraw, and the bank refuses a withdrawal that would go below zero. The rules travel with the money.
A class is that: data plus the only ways it is allowed to change. The rule that must always hold, "never below zero", is called an invariant. A dataclass is the short form for when there are no rules, just named fields.
A class bundles data with its rules
A class keeps data together with the methods that are allowed to change it. The point is the invariant: a fact that is always true about an object, like "a wallet balance is never negative". Methods check the rule before they change anything, so a rejected call leaves the object as it was.
class Wallet:
def __init__(self, owner, balance=0):
if balance < 0:
raise ValueError("balance cannot be negative")
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def pay(self, amount):
if amount <= 0 or amount > self._balance:
raise ValueError(f"cannot pay {amount}")
self._balance -= amount
w = Wallet("asha", 100)
w.pay(30)
try:
w.balance = 1_000
except AttributeError:
print("balance is read-only:", w.balance)
Output from a real run
balance is read-only: 70
Properties: attributes with code behind them
@property turns a method into something read like an attribute. Without a setter it is read-only. With @name.setter, assignments run your validation. Store one source of truth and compute the rest, so derived values never go stale.
class Trip:
def __init__(self, km):
self.km = km
@property
def km(self):
return self._km
@km.setter
def km(self, value):
if value < 0:
raise ValueError("distance cannot be negative")
self._km = value
@property
def miles(self):
return round(self._km * 0.621371, 2)
t = Trip(10)
t.km = 16
print("16 km in miles:", t.miles)
Output from a real run
16 km in miles: 9.94
Alternate constructors
A @classmethod receives the class as cls, so cls(...) builds an instance of whichever class it was called on, subclasses included. It is the idiomatic home for "build one from a CSV line / a dict / an API payload". A @staticmethod receives neither the instance nor the class: a plain function kept in the class's namespace.
Dataclasses
@dataclass writes __init__, __repr__ and __eq__ from annotated fields. It is the right tool for records: rows, events, config. Mutablemutable: Mutable objects (lists, dicts, sets) can be changed in place. Immutable ones (ints, strings, tuples) cannot, so "changing" them makes a new object. Learn more → defaults need field(default_factory=list); a plain [] is refused because it would be shared. frozen=True makes instances immutable and hashablehashable: A value whose hash never changes, so it can be a dict key or a set member: numbers, strings, tuples of hashable values. Lists and dicts are not. Learn more →.
from dataclasses import dataclass, field @dataclass class Delivery: order_id: str minutes: int notes: list = field(default_factory=list) @classmethod def from_csv(cls, line): order_id, minutes = line.split(",") return cls(order_id.strip(), int(minutes)) d = Delivery.from_csv("o7, 35") print(d) print("equal to Delivery('o7', 35):", d == Delivery("o7", 35))
Output from a real run
Delivery(order_id='o7', minutes=35, notes=[])
equal to Delivery('o7', 35): TrueDelivery("o1", "35") happily stores a string. Convert in the alternate constructor or in __post_init__, or use pydantic when inputs are untrusted.Common mistakes
- Public attributes for values with rules — Anyone can set an invalid value. Use a property with validation.
- Storing derived values — They go stale. Compute them in a property.
- @staticmethod for alternate constructors — Subclasses get the base class back. Use @classmethod and cls(...).
Key takeaways
- Methods protect invariants: validate, then change state.
- Properties make attributes read-only or validated.
- @classmethod alternate constructors return the right subclass.
- Dataclasses generate the boilerplate; mutable defaults need default_factory.
Interview prep
THE QUESTION
"When would you use a dataclass instead of a dict for a record?"
Avoid: "getters and setters for every attribute". In Python start with plain attributes and add @property only where a rule or a computed value is needed.
Follow-ups · answer out loud, then open
Follow-up"@classmethod, @staticmethod and a normal method: what does each receive?"
Scenario"Model an order record parsed from JSON, with validation and type conversion."
Trap"Dataclasses check field types at run time."
Check yourself
3 questionsAssigning to a property that has no setter raises...
Show the answer
AttributeError. The property defines no way to set it.
Why does @dataclass refuse tags: list = []?
Show the answer
All instances would share one list. Use field(default_factory=list).
Sub.from_csv(...) defined as a classmethod in Base returns...
Show the answer
A Sub. cls is the class it was called on.
Practise this
Problems that use this, graded on hidden tests
- Bank Account with ValidationOOP & classes Easy
- Temperature with PropertiesOOP & classes Easy
- Build Records from CSV RowsOOP & classes Medium
Keep going
Up next · Classes and robust code · lesson 2 of 2 · 5 min readExceptions and context managers
try/except/else/finally, custom exceptions, with blocks, contextlib and logging.
Related lessons
Previous: Iterators, yield from and itertools
Primary sources: dataclasses · Built-in property