Small Classes
A class describes how to make a kind of object.
Here is a small class:
Create an object by calling the class:
__init__ initializes the object
__init__ runs when a new object is created. It receives the values passed to
the class call:
ScoreRecord("Ada", 8)
Inside __init__, self means the new object being built.
Those lines store attributes on the object.
Create a small record object
Ready to run.
Keep classes small at first
A class is useful when the data has a stable shape and a name in the problem.
Good early examples:
ScoreRecordExperimentConfigTrainingResult
Poor early examples:
- a class that only hides one number;
- a class created because code “should use objects”;
- a class with many unrelated responsibilities.
Why not always use dictionaries?
A dictionary is excellent for flexible data. A class is useful when the fields are known and repeated.
This is easier to mistype:
record["scroe"]
With an object or dataclass, the intended field names are more visible in the definition.
What expression creates a ScoreRecord for name "Lin" and score 9?
Answer it first, then check.
HintCall the class
Put the two constructor arguments inside parentheses after ScoreRecord.
SolutionConstruct the record
ScoreRecord("Lin", 9) calls the class with the required name and score and
returns the new object.