Creating a dataclass
Dataclasses can provide even richer ways of storing and working with data. Previously we used a namedtuple on weight log entries to make a nice easy to use data structure. In this code, we're going to use a dataclass to do the same thing, but add a custom property
to return the body mass to flipper length ratio. Dataclasses start with a collection of fields and their types. Then you define any properties, which are functions on the dataclass that operate on itself to return additional information about the data. For example, a person dataclass might have a property that calculates someone's current age based on their birthday and the current date.
This exercise is part of the course
Data Types in Python
Exercise instructions
- Import
dataclass
fromdataclasses
. - Add the
species
(string
),sex
(string
),body_mass
(int
), andflipper_length
(int
) fields to the dataclass. - Add a property (
mass_to_flipper_length_ratio
) that returns thebody_mass
divided by theflipper_length
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import dataclass
from ____ import ____
@____
class WeightEntry:
# Define the fields on the class
____: str
____: int
____: int
____: str
# Define a property that returns the body_mass / flipper_length
____
____ mass_to_flipper_length_ratio(____):
return ____.body_mass / ____.____