Pythonのdataclass
は、クラスの定義を簡単にするためのデコレータです。このデコレータは、クラスのフィールド(型注釈が付いたクラス変数)を見つけ、それらのフィールドに基づいて特殊メソッド(__init__
、__repr__
など)を自動的に生成します。
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
上記の例では、InventoryItem
クラスはname
、unit_price
、quantity_on_hand
という3つのフィールドを持ちます。これらのフィールドは、自動生成される__init__
メソッドの引数となります。
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
self.name = name
self.unit_price = unit_price
self.quantity_on_hand = quantity_on_hand
dataclass
デコレータは、フィールドの順序を保持します。つまり、生成されるメソッドのフィールドの順序は、クラス定義内でのフィールドの順序と一致します。
しかし、order
パラメータがFalse
(デフォルト)の場合、dataclass
は順序付けのための特殊メソッド(__lt__
、__le__
、__gt__
、__ge__
)を生成しません。これらのメソッドが必要な場合(例えば、クラスのインスタンスを特定のフィールドに基づいてソートしたい場合)、order
パラメータをTrue
に設定することで生成できます。
@dataclass(order=True)
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
以上がPythonのdataclass
とその順序性についての基本的な説明です。この機能を活用することで、Pythonでのクラス定義がより簡単になり、コードの可読性も向上します。