Loading lesson…
Classes group state and behavior. Dataclasses cut boilerplate. Let AI scaffold while you understand what's under the hood.
Reach for a class when you have state that changes over time plus behavior that acts on it. A bank account has a balance and methods that mutate it. That is a class.
from dataclasses import dataclass, field
@dataclass
class Account:
owner: str
balance: float = 0.0
history: list[str] = field(default_factory=list)
def deposit(self, amount: float) -> None:
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
self.history.append(f"+{amount:.2f}")
def withdraw(self, amount: float) -> None:
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
self.history.append(f"-{amount:.2f}")
acc = Account("Ada")
acc.deposit(100)
acc.withdraw(30)
print(acc.balance, acc.history)@dataclass generates __init__, __repr__, and __eq__ for free. Modern Python almost never writes raw classes.@dataclass
class SavingsAccount(Account):
rate: float = 0.02
def accrue(self) -> None:
interest = self.balance * self.rate
self.deposit(interest)
s = SavingsAccount("Bo", balance=1000.0)
s.accrue()
print(s.balance) # 1020.0Inheritance shines when the subclass genuinely is-a parent. Do not inherit just to share code.The big idea: classes tie state to behavior, dataclasses remove boilerplate, and inheritance is a last resort, not a first move.
15 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-progx-python-oop-creators
What is the bug in this code? class Counter: count = []
What does using `default_factory=list` in a dataclass field accomplish?
A developer wants to model a 'Vehicle' that 'has a' Engine. Should they use inheritance or composition?
What does the @dataclass decorator automatically generate for a class?
Why does the lesson advise that 'inheritance is a last resort, not a first move'?
A student writes: class Person: def speak(self): print('Hello'). What is 'self' in this context?
What problem does using a dataclass solve compared to a regular class with just attributes?
Why might an AI coding assistant suggest deep inheritance trees when writing Python code?
What is the fundamental idea behind 'composition over inheritance'?
What does it mean that 'classes tie state to behavior'?
When is inheritance the right choice in Python?
What happens if you define a dataclass field with `default=` instead of `default_factory=` for a mutable value like a list?
What distinguishes a method from a regular function defined at module level?
A programmer needs a class that only holds data fields with no custom behavior. What Python feature is most appropriate?
What is wrong with this code: def greet(names=[]): print(names)?