ペップ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日目。
dataclasses
Pythonバージョン3.7未満でモジュールを使用する場合は、バックポートされたモジュール(3.6 が必要) またはattrs
上記のプロジェクトを使用します。