BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Data Types in Python

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • 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.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# 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 / ____.____
Kodu Düzenle ve Çalıştır