LoginSignup
0
0

@dataclassをちょっと理解する

Last updated at Posted at 2024-02-04

環境

python: 3.12

dataclassを使わない場合の書き方

class Point:
    def __init__(self, x, y):
        self.x: str = x
        self.y: str = y

    def __repr__(self):
        return f"Point({self.x}, {self.y})"

    def __eq__(self, other):
        if isinstance(other, Point):
            return self.x == other.x and self.y == other.y
        return False

    def __hash__(self):
        return hash((self.x, self.y))

    # ...etc
    

print("__init__")
point1 = Point(1, 2)
point2 = Point(1, 2)

print("__repr__")
print(point1)  # Point(1, 2)
print(point2)  # Point(1, 2)

print("__eq__")
print(point1 == point2)  # True

print("__hash__")
point_set = {point1}
print(point_set)  # {Point(1, 2)}
print(point2 in point_set)  # True

dataclassを使う場合の書き方(frozen=False)

from dataclasses import dataclass


@dataclass
class Point:
    x: int
    y: int

# クラスの使い方
print("__init__")
point1 = Point(1, 2)
point2 = Point(1, 2)

print("__repr__")
print(point1)  # Point(1, 2)
print(point2)  # Point(1, 2)

print("__eq__")
print(point1 == point2)  # True

# print("__hash__")
# point_set = {point1}  # エラー
# print(point_set)  # {Point(1, 2)}
# print(point2 in point_set)  # True

print(point1.x)  # 1
point1.x = 3
print(point1.x)  # 3

dataclassを使う場合の書き方(frozen=True)

from dataclasses import dataclass


@dataclass(frozen=True)
class Point:
    x: int
    y: int


# クラスの使い方
print("__init__")
point1 = Point(1, 2)
point2 = Point(1, 2)

print("__repr__")
print(point1)  # Point(1, 2)
print(point2)  # Point(1, 2)

print("__eq__")
print(point1 == point2)  # True

print("__hash__")
point_set = {point1}
print(point_set)  # {Point(1, 2)}
print(point2 in point_set)  # True

print(point1.x)  # 1
point1.x = 3  # エラー
0
0
1

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