1. Learn
  2. /
  3. Courses
  4. /
  5. Data Types for Data Science in Python

Exercise

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.

Instructions

100 XP
  • Import dataclass from dataclasses.
  • Add the species (string), sex (string), body_mass (int), and flipper_length (int) fields to the dataclass.
  • Add a property (mass_to_flipper_length_ratio) that returns the body_mass divided by the flipper_length.