Classes and objects
Define the lab goal and success criteria
A class defines how related state and behavior belong together; each instance receives its own attributes through `__init__`.
1Try it yourself
Playground
Object form builder
Build a Message class mentally: fields role + content, then call preview().
class Message: # role… # content… # preview()…
Before you start
Why this matters
Before running anything, predict one observable result from the case: two threshold models use the same prediction behavior but need different names and cutoffs. Write the prediction beside the command or code line that should cause it. This makes the session an experiment rather than a transcription exercise.
2Learn the idea
Read
Explain the chapter step
Begin by writing the success condition in observable terms. For this case, success is not familiarity with the vocabulary; it is producing a TinyModel class whose instances validate thresholds, predict independently, and describe themselves. Record the starting state so you can distinguish an improvement from a result that was already present.
On this page, the practical job is to state a measurable outcome before changing anything. The running case is two threshold models use the same prediction behavior but need different names and cutoffs.
Read
Run the working example
class TinyModel:
def __init__(self, name, threshold=0.5):
if not 0 <= threshold <= 1:
raise ValueError("threshold must be between 0 and 1")
self.name = name
self.threshold = threshold
def predict(self, score):
return score >= self.threshold
strict = TinyModel("strict", 0.8)
friendly = TinyModel("friendly", 0.4)
print(strict.predict(0.6), friendly.predict(0.6))
Expected evidence:
False True
The output may include version-specific details such as hashes, paths, fitted thresholds, or final decimal places. Compare the structural facts described here rather than copying placeholders. If the structure differs, stop and inspect the earliest unexpected line.
Read
Read it line by line
- the class statement creates a new type; it does not create an instance.
__init__runs once per construction and rejects impossible thresholds early.self.nameandself.thresholdbelong to that particular object.predictreceives the instance automatically when called throughstrictorfriendly.
These lines form one chain: a model name, a threshold, and numeric scores passed to predict becomes Boolean predictions determined by each instance's own threshold. Change only one input first. When several values change together, you cannot tell which change caused the new behavior.
Read
Common errors and fixes
- First failure: omitting
selffrom a method produces an argument-count error when the method is called. Re-run the smallest command that proves the repair. - Second failure: writing
thresholdinstead ofself.thresholdinsidepredictloses access to instance state. Preserve the failing input as a test when it represents a realistic mistake. - Misleading success: a mutable class attribute such as
history = []is shared; createself.history = []inside__init__instead. A clean-looking final line cannot cancel contradictory intermediate evidence.
When debugging, copy the exact error text and inspect names, paths, shapes, types, and versions. Explain the cause in one sentence before changing code. That discipline prevents a guessed repair from creating a second defect.
Read
Evidence for this stage
Create two instances and prove changing friendly.threshold does not change strict.threshold. Test scores below, equal to, and above the cutoff, plus invalid thresholds such as 1.2.
For the current explain step, save the smallest useful evidence: the relevant command, its output, and the input that produced it. Do not use a screenshot as the only record when text can be copied and searched. Keep generated artifacts separate from source inputs so rerunning the example does not destroy the evidence it is meant to evaluate.
Export the class from a small module with type hints and examples. Users should know construction parameters, method return types, and which validation errors are intentional.
Read
Reflect on the result
Return to your opening prediction. Mark it correct or rewrite it with the condition you missed. Then explain the difference between a successful execution and a trustworthy result for this specific example.
Continue learning · glossary & guides
- Which line or command establishes the current step's most important fact?
- What output would reveal that omitting
selffrom a method produces an argument-count error when the method is called? - Can a new user reproduce a
TinyModelclass whose instances validate thresholds, predict independently, and describe themselves from the stated setup?