0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python dataclassについて

Posted at

使い方

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

p = Person("Alice", 30)
print(p)
Person(name='Alice', age=30)

何が嬉しいか?

いくつかの特殊メソッドが自動生成されます。

これにより、dataclassを使わない場合と比較して、いくつかの利用シーンにおいて記述が少なくて済みます。
例えば、特殊メソッド__repr__()などを利用したいシーン(printによってobjectの情報を標準出力したいシーン)において、通常のclassでは以下のように自前で実装する必要がありますが、dataclassでは不要です。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f'Person(name={self.name}, age={self.age})'


p = Person("Alice", 30)
print(p)
Person(name=Alice, age=30)

特殊メソッド __eq__() も自動生成されるので、等価比較ができるようになります。

u1 = Person("Taro", 20)
u2 = Person("Taro", 20)
print(u1 == u2)

特殊メソッド __lt__()__gt__() も自動生成されるので、大小関係の比較ができるようになります。

@dataclass(order=True)
class Task:
    priority: int
    name: str
t1 = Task(1, "A")
t2 = Task(2, "B")
print(t1 < t2
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?