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.
Questo esercizio fa parte del corso
Data Types in Python
Istruzioni dell'esercizio
- Import
dataclassfromdataclasses. - 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_massdivided by theflipper_length.
Esercizio pratico interattivo
Prova a risolvere questo esercizio completando il codice di esempio.
# 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 / ____.____