What are data classes and how are they different from common classes?

PEP 557 introduces data classes into the Python standard library. It says that by applying the @dataclass decorator shown below, it will generate "among other things, an __init__()".

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """Class for keeping track of an item in inventory."""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

It also says dataclasses are "mutable namedtuples with default", but I don't understand what this means, nor how data classes are different from common classes.

What are data classes and when is it best to use them?

← Назад к списку