データクラスとは何ですか?一般的なクラスとどう違うのですか?質問する

データクラスとは何ですか?一般的なクラスとどう違うのですか?質問する

ペップ557Python標準ライブラリにデータクラスを導入します。@dataclass以下に示すデコレータを使用すると、「とりわけ」が生成されます__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

また、データクラスは「デフォルトを持つ変更可能な名前付きタプル」であるとも書かれていますが、これが何を意味するのか、またデータクラスが一般的なクラスとどう違うのかはわかりません。

データ クラスとは何ですか? また、いつ使用するのが最適ですか?

ベストアンサー1

データ クラスは、多くのロジックを含むのではなく、状態を保存することに特化した通常のクラスです。主に属性で構成されるクラスを作成するたびに、データ クラスを作成します。

このdataclassesモジュールは、データ クラスの作成を容易にします。多くの定型文を自動で処理します。

これは、データ クラスがハッシュ可能である必要がある場合に特に便利です。これは、__hash__メソッドだけでなくメソッドも必要になるためです__eq__。デバッグを容易にするためにカスタム__repr__メソッドを追加すると、非常に冗長になる可能性があります。

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

    def __init__(
            self, 
            name: str, 
            unit_price: float,
            quantity_on_hand: int = 0
        ) -> None:
        self.name = name
        self.unit_price = unit_price
        self.quantity_on_hand = quantity_on_hand

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand
    
    def __repr__(self) -> str:
        return (
            'InventoryItem('
            f'name={self.name!r}, unit_price={self.unit_price!r}, '
            f'quantity_on_hand={self.quantity_on_hand!r})'
        )

    def __hash__(self) -> int:
        return hash((self.name, self.unit_price, self.quantity_on_hand))

    def __eq__(self, other) -> bool:
        if not isinstance(other, InventoryItem):
            return NotImplemented
        return (
            (self.name, self.unit_price, self.quantity_on_hand) == 
            (other.name, other.unit_price, other.quantity_on_hand))

次のようdataclassesに削減できます。

from dataclasses import dataclass

@dataclass(unsafe_hash=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

(例:PEPの例)。

同じクラス デコレータは、比較メソッド ( __lt____gt__など) を生成し、不変性を処理することもできます。

namedtupleクラスもデータクラスですが、デフォルトでは不変です(シーケンスでもあります)。dataclassesこの点でははるかに柔軟であり、簡単に構造化できるので、namedtupleクラスと同じ役割を果たす

PEPは、attrsプロジェクト、さらに多くのことが可能になります(スロット、バリデーター、コンバーター、メタデータなどを含む)。

いくつかの例を見たい方は、私が最近dataclassesいくつかのコードの到来ソリューションについては、ソリューションを参照してください7日目8日目11日目そして20日目

dataclassesPythonバージョン3.7未満でモジュールを使用する場合は、バックポートされたモジュール(3.6 が必要) またはattrs上記のプロジェクトを使用します。

おすすめ記事