简体   繁体   中英

Dataclass error, can't figure out the solutions

Guys I stumbled across the problem with dataclass. I am new to coding so perhaps there is a problem with inheritance. My main aim is to hide innit. But after importing dataclass I got the problem in VSCode: "Fields without default values cannot appear after fields with default values".

That is my code. How can I tackle the issue?

from ast import Return
from typing import Dict, Type
from dataclasses import dataclass

@dataclass
class InfoMessage:
    """Информационное сообщение о тренировке."""
    training_type: str
    duration: float
    distance: float
    speed: float
    calories: float

    def get_message(self):
        FINAL_TEXT=(f"Тип тренировки: {self.training_type}; "
                    f"Длительность: {self.duration:.3f} ч.; "
                    f"Дистанция: {self.distance:.3f} км; "
                    f"Ср. скорость: {self.speed:.3f} км/ч; "
                    f"Потрачено ккал: {self.calories:.3f}.")
        return FINAL_TEXT


@dataclass
class Training:
    """Базовый класс тренировки."""
    action: int
    duration: float
    weight: float
    LEN_STEP: float = 0.65
    M_IN_KM: float = 1000

    def get_distance(self) -> float:
        """Получить дистанцию в км."""
        return (self.action * self.LEN_STEP / self.M_IN_KM)
        
    def get_mean_speed(self) -> float:
        """Получить среднюю скорость движения."""
        return Training.get_distance(self) / self.duration

    def get_spent_calories(self) -> float:
        """Получить количество затраченных калорий."""
        raise NotImplementedError

    def show_training_info(self) -> InfoMessage:
        """Вернуть информационное сообщение о выполненной тренировке."""
        info = InfoMessage(self.__class__.__name__,
                           self.duration,
                           self.get_distance(),
                           self.get_mean_speed(),
                           self.get_spent_calories())
        return info


class Running(Training):
    """Тренировка: бег."""

    def get_spent_calories(self):
        speed = self.get_mean_speed()
        MINUTES_IN_H: float = 60
        COEFF_1: float = 18
        COEFF_2: float = 20
        return ((COEFF_1 * speed - COEFF_2) * self.weight
                / Training.M_IN_KM * self.duration * MINUTES_IN_H)

@dataclass
class SportsWalking(Training):
    """Тренировка: спортивная ходьба."""
    action: float
    duration: float
    weight: float
    height: float
    super().__init__(action, duration, weight)

    def get_spent_calories(self):
        speed = Running.get_mean_speed(self)
        MINUTES_IN_H: float = 60
        KAF_1: float = 0.035
        KAF_2: float = 0.029
        cals_walk = ((KAF_1 * self.weight + (speed ** 2 // self.height)
                     * KAF_2 * self.weight) * self.duration * MINUTES_IN_H)
        return cals_walk


@dataclass
class Swimming(Training):
    """Тренировка: плавание."""
    LEN_STEP: float = 1.38
    action: int
    duration: float
    weight: float
    length_pool: float
    count_pool: float
    
    LEN_STEP: float = 1.38        
    super().__init__(action, duration, weight)

    def get_mean_speed(self) -> float:
        mean_speed = (self.length_pool * self.count_pool
                      / self.M_IN_KM / self.duration)
        return mean_speed

    def get_spent_calories(self) -> float:
        KAF_1: float = 1.1
        KAF_2: float = 2
        speed = Swimming.get_mean_speed(self)
        cals = (speed + KAF_1) * KAF_2 * self.weight
        return cals

    def get_distance(self) -> float:
        LEN_STEP: float = Swimming.LEN_STEP
        dist = self.action * LEN_STEP / self.M_IN_KM
        return dist


def read_package(workout_type: str, data: list) -> Training:
    """Прочитать данные полученные от датчиков."""
    defenition: Dict[str, Type[Training]] = {"SWM": Swimming,
                                             "RUN": Running,
                                             "WLK": SportsWalking}

    action = defenition[workout_type]
    final = action(*data)
    return final


def main(training: Training) -> None:
    """Главная функция."""
    info = training.show_training_info()
    print(info.get_message())


if __name__ == '__main__':
    packages = [('SWM', [720, 1, 80, 25, 40]),
                ('RUN', [15000, 1, 75]),
                ('WLK', [9000, 1, 75, 180])]

    for workout_type, data in packages:
        training = read_package(workout_type, data)
        main(training)

You error message tells you what is wrong with your code: Fields without default values cannot appear after fields with default values

This means that you cannot have

@dataclass
class Test:
    attribute1: str = "value"
    attribute2: int

Or in your case:

@dataclass
class Swimming(Training):
    """Тренировка: плавание."""
    # Move this --> LEN_STEP: float = 1.38
    action: int
    duration: float
    weight: float
    length_pool: float
    count_pool: float
    LEN_STEP: float = 1.38 # <-- Move here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM