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?

@dataclassデコレータとfield

Last updated at Posted at 2024-11-22

素人のメモなのでたぶんあってますくらい。
デコレータについては他記事で補完してください。

まずは@dataclassの話

@dataclassデコレータ:Pythonでクラスを簡単に作ることができる(3つのメソッドを勝手に実行してくれる)。

@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})"
    #インスタンス同士の属性が同じか確認するメソッド
    def __eq__(self, other): if isinstance(other, Person): return self.name == other.name and self.age == other.age return

@dataclassを使うと、もっと簡単に書ける(3メソッドが勝手に実行され、initの属性指定だけ書く):

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

これだけで、__init____repr____eq__が自動的に追加される。

次に、field(default_factory=str)の話

field:dataclassesモジュール内で定義されている関数フィールドのデフォルト値を設定するために使う。
例えば、空の文字列や空のリストをデフォルト値にしたいときに使う。

from dataclasses import dataclass, field

@dataclass
class Example:
    name: str = field(default_factory=str)  # デフォルトは空の文字列
    values: list = field(default_factory=list)  # デフォルトは空のリスト

このクラスを使うと、nameはデフォルトで空の文字列、valuesはデフォルトで空のリストになる。

インスタンス作成withデフォルト値(空)

example = Example()
print(example.name)   # 出力: ''
print(example.values) # 出力: []

インスタンス作成with指定した値

example_with_custom_values = Example(name="Alice", values=[1, 2, 3])
print(example_with_custom_values.name)   # 出力: 'Alice'
print(example_with_custom_values.values) # 出力: [1, 2, 3]

たぶんfieldはもっと使い方ある、、、、

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?