Classes and dataclasses
Group data with the behaviour that belongs to it.
What you will be able to do
- Define a class with methods
- Generate boilerplate with @dataclass
- Avoid shared mutable state
A class describes a kind of object: its data and the operations that make sense for that data. A dataclass writes the constructor and comparison methods for you.
from dataclasses import dataclass, field
@dataclass
class Learner:
name: str
scores: list[int] = field(default_factory=list)
def average(self) -> float:
return sum(self.scores) / len(self.scores) if self.scores else 0.0
def passed(self, mark: float = 75) -> bool:
return self.average() >= mark
ada = Learner("Ada", [88, 92, 79])
print(ada)
print(f"{ada.average():.1f}")
print(ada.passed())- Class
- A template that describes objects.
- Instance
- One object created from a class.
- Attribute
- Data stored on an instance.
- Method
- A function defined on a class.
- Dataclass
- A decorator that generates common methods.
Your turn
MediumAdd a score method
Extend the Learner class with add_score() and print the updated average for a learner with two scores.
PYTHON · starter
from dataclasses import dataclass, field
@dataclass
class Learner:
name: str
scores: list[int] = field(default_factory=list)
# add add_score() and average()
Check your understanding before moving on.
Knowledge checkQuestion 1
What does @dataclass generate by default?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.