<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>「default」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/default/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Mon, 01 Dec 2025 21:05:36 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「default」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】dataclassの使い方の基本</title>
		<link>https://tech.nkhn37.net/python-dataclass-basics/</link>
					<comments>https://tech.nkhn37.net/python-dataclass-basics/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Sun, 03 Sep 2023 20:00:00 +0000</pubDate>
				<category><![CDATA[dataclasses]]></category>
		<category><![CDATA[dataclass]]></category>
		<category><![CDATA[default]]></category>
		<category><![CDATA[default_factory]]></category>
		<category><![CDATA[field]]></category>
		<category><![CDATA[frozen]]></category>
		<category><![CDATA[デコレーター]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=9039</guid>

					<description><![CDATA[Python でデータクラスを作成する際に便利な @dataclass デコレータの使い方について解説します。 @dataclass デコレーター Python のクラスを作成する際には、通常、インスタンス生成時の初期化 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Python でデータクラスを作成する際に便利な <span class="jinr-d--text-color d--marker1 d--bold"><code>@dataclass</code> デコレータの使い方</span>について解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold"><code>@dataclass</code> デコレーター</h2>



<p class="wp-block-paragraph">Python のクラスを作成する際には、通常、インスタンス生成時の初期化のための <code>__init__()</code> メソッドを定義します。クラス定義については「<a href="https://tech.nkhn37.net/python-class-definition/" data-type="link" data-id="https://tech.nkhn37.net/python-class-definition/" target="_blank" rel="noreferrer noopener">クラスの定義と使い方</a>」を参考にしてください。</p>



<p class="wp-block-paragraph">プログラミングでは、データを表現するだけのためにクラスを使う場合がよくあります。例えば、2 次元の位置を表すような点を表現するような場合が代表的です。このような場合には、<span class="jinr-d--text-color d--marker1 d--bold"><code>@dataclass</code></span> デコレータを使用することで冗長な初期化などのメソッドを書くことなく簡潔にクラス定義ができます。</p>



<p class="wp-block-paragraph">この記事では、簡単なデータクラスの定義例を使いながら <span class="jinr-d--text-color d--marker1 d--bold"><code>@dataclass</code> デコレータの使い方の基本</span>を紹介します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">一般的なデータクラスの定義</h3>



<p class="wp-block-paragraph">簡単な例として、2 次元の点を表す <code>Point</code> クラスを <code>@dataclass</code> デコレータを<span class="jinr-d--text-color d--marker2">使わない</span>一般的な方法で作成してみます。これにより <code>@dataclass</code> を使った時にどういったメリットがあるのかが分かりやすいかと思います。<code>@dataclass</code> デコレータの使い方を知りたいだけという場合は、読み飛ばしてもらって構いません。</p>



<p class="wp-block-paragraph">一般的なデータクラスの定義方法は、以下のようになります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Point:
    """位置クラス"""

    def __init__(self, x, y):
        """コンストラクタ"""
        self.x = x
        self.y = y

    def __repr__(self):
        """位置のテキスト表現を返す"""
        return f"Point(x={self.x}, y={self.y})"

    def __add__(self, other):
        """+演算子"""
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        """-演算子"""
        return Point(self.x - other.x, self.y - other.y)

    def __eq__(self, other):
        """等価比較"""
        return self.x == other.x and self.y == other.y


if __name__ == "__main__":
    point1 = Point(1, 1)
    point2 = Point(2, 2)
    point3 = Point(1, 1)

    print(point1)
    print(point2)
    print(point1 + point2)
    print(point1 - point2)
    print(point1 == point3)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
Point(x=1, y=1)
Point(x=2, y=2)
Point(x=3, y=3)
Point(x=-1, y=-1)
True </pre>



<p class="wp-block-paragraph">上記例では、<code>x</code> と <code>y</code> の値を持つような <code>Point</code> クラスを定義しています。<code>Point</code> クラス内では、以下のようなメソッドを定義しています。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>メソッド</th><th>内容</th></tr></thead><tbody><tr><td><code>__init__()</code></td><td>インスタンスを初期化するコンストラクタ</td></tr><tr><td><code>__repr__()</code></td><td>インスタンスが <code>print</code> 文に渡された際の表示形式を定義</td></tr><tr><td><code>__add__()</code></td><td><code>Point</code> 同士の加算を定義</td></tr><tr><td><code>__sub__()</code></td><td><code>Point</code> 同士の減算を定義</td></tr><tr><td><code>__eq__()</code></td><td><code>Point</code> 同士の等価比較する</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">上記のようなメソッドを定義をすることで、<code>Point</code> というデータのインスタンスを作成し、加算・減算したり、等価比較したりすることができるようになります。</p>



<p class="wp-block-paragraph">データ専用クラスの場合は、上記のようにコンストラクタや文字列表現、等価比較等の定型的なコード（ボイラープレートコード）を書く必要があります。<code>@dataclass</code> デコレータを使用することで、こういった定型コードの作成を省略することができます。</p>



<h3 class="wp-block-heading jinr-heading d--bold">@dataclassデコレータの使い方</h3>



<p class="wp-block-paragraph"><span class="jinr-d--text-color d--marker1 d--bold"><code>@dataclass</code></span> デコレータの使い方を例を使って紹介していきます。</p>



<h4 class="wp-block-heading jinr-heading d--bold">基本的な使い方</h4>



<p class="wp-block-paragraph">上記の一般的なクラス定義例で紹介した 2 次元の点を表す <code>Point</code> クラスを <code>@dataclass</code> を使って定義すると以下のようになります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from dataclasses import dataclass


@dataclass
class Point:
    """位置クラス"""

    x: int
    y: int

    def __add__(self, other):
        """+演算子"""
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        """-演算子"""
        return Point(self.x - other.x, self.y - other.y)


if __name__ == "__main__":
    point1 = Point(1, 1)
    point2 = Point(2, 2)
    point3 = Point(1, 1)

    print(point1)
    print(point2)
    print(point1 + point2)
    print(point1 - point2)
    print(point1 == point3)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
Point(x=1, y=1)
Point(x=2, y=2)
Point(x=3, y=3)
Point(x=-1, y=-1)
True </pre>



<p class="wp-block-paragraph"><code>@dataclass</code> デコレータを使う場合は、クラス定義で「<span class="jinr-d--text-color d--marker1 d--bold"><code>@dataclass</code></span>」をつけます。</p>



<p class="wp-block-paragraph"><code>@dataclass</code> デコレータをクラス定義に付与すると、<code>Point</code> の情報を読み込み、自動で <code>__init__()</code>、<code>__repr__()</code>、<code>__eq__()</code> といったメソッドを生成します。<code>__eq__()</code> メソッドはインスタンスの全ての属性が等しいかどうかで等価を判定します。</p>



<p class="wp-block-paragraph">なお、<code>__add__()</code> や <code>__sub__()</code> は自動生成されないので個別に定義しています。</p>



<p class="wp-block-paragraph"><code>@dataclass</code> デコレータを使わない場合に比べて、定型的なコード（ボイラープレートコード）が減り、すっきりとした定義できています。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox5 ">
			<i class="jif jin-ifont-v2speaker" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><code>@dataclass</code> デコレータで作成されるメソッドを調べたい場合は、<code>help</code> を使うと確認できます。例えば、クラス定義後に「<code>help(Point)</code>」を表示すると以下のようになります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Help on Point in module __main__ object:
class Point(builtins.object)
 |  Point(x: int, y: int) -> None
 |  
 |  位置クラス
 |  
 |  Methods defined here:
 |  
 |  __add__(self, other)
 |      +演算子
 |  
 |  __eq__(self, other)
 |      Return self==value.
 |  
 |  __init__(self, x: int, y: int) -> None
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  __sub__(self, other)
 |      -演算子
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __annotations__ = {'x': &lt;class 'int'>, 'y': &lt;class 'int'>}
 |  
 |  __dataclass_fields__ = {'x': Field(name='x',type=&lt;class 'int'>,default...
 |  
 |  __dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,or...
 |  
 |  __hash__ = None
 |  
 |  __match_args__ = ('x', 'y')</pre>



<p class="wp-block-paragraph"><code>__init__()</code> や <code>__eq__()</code>、<code>__repr()__</code> といったメソッドが定義されていることが分かります。</p>
</div>
		</div></section>



<h4 class="wp-block-heading jinr-heading d--bold">イミュータブル（immutable）なデータクラスを定義する <code>frozen</code></h4>



<p class="wp-block-paragraph"><code>@dataclass</code> デコレータは、他にも便利な機能がありますので紹介します。</p>



<p class="wp-block-paragraph">例えば、ハッシュ可能として辞書のキーに使ったり、集合に追加するために <code>Point</code> を変更不可 (immutable) として定義する場合があります。この場合には、<span class="jinr-d--text-color d--marker1 d--bold"><code>frozen=True</code></span> という引数を <code>@dataclass</code> デコレータの引数に追加します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from dataclasses import dataclass


@dataclass(frozen=True)
class FrozenPoint:
    """位置クラス"""

    x: int
    y: int

    def __add__(self, other):
        """+演算子"""
        return FrozenPoint(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        """-演算子"""
        return FrozenPoint(self.x - other.x, self.y - other.y)


if __name__ == "__main__":
    point1 = FrozenPoint(1, 1)

    point1.x = 2
    print(point1)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
Traceback (most recent call last):
...(省略)...
dataclasses.FrozenInstanceError: cannot assign to field 'x'</pre>



<p class="wp-block-paragraph"><code>frozen=True</code> を指定すると、<code>x</code> や <code>y</code> の値は定義後に変更できなくなります。例では、<code>point1.x = 2</code> のように <code>x</code> の値を変更しようとしていますが例外となります。</p>



<h4 class="wp-block-heading jinr-heading d--bold"><code>dataclass</code> の引数</h4>



<p class="wp-block-paragraph"><code>＠dataclass</code> の <code>frozen</code> 引数を紹介しましたが、他にも多くの引数が存在します。詳細は公式ドキュメントの<a href="https://docs.python.org/ja/3/library/dataclasses.html" target="_blank" rel="noreferrer noopener">こちら</a>を参照してください。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>引数</th><th>デフォルト</th><th>概要</th></tr></thead><tbody><tr><td><code>init</code></td><td><code>True</code></td><td><code>__init__()</code> メソッドを生成します。</td></tr><tr><td><code>repr</code></td><td><code>True</code></td><td><code>__repr__()</code> メソッドを生成します。</td></tr><tr><td><code>eq</code></td><td><code>True</code></td><td><code>__eq__()</code> メソッドを生成します。</td></tr><tr><td><code>order</code></td><td><code>False</code></td><td><code>True</code> に設定するとインスタンスを比較するためのメソッド (<code>__lt__()</code>, <code>__le__()</code>, <code>__gt__()</code>, <code>__ge__()</code>) が生成されます。</td></tr><tr><td><code>unsafe_hash</code></td><td><code>False</code></td><td><code>True</code> に設定すると <code>__hash__()</code> メソッドが生成され、インスタンスをハッシュ可能にします。</td></tr><tr><td><code>frozen</code></td><td><code>False</code></td><td><code>True</code> に設定するとクラスを変更できない immutable にし、ハッシュ可能になります。</td></tr><tr><td><code>match_args</code></td><td><code>True</code></td><td><code>__match_args__</code> が <code>__init__</code> に渡されたパラメータリストから作成されます。</td></tr><tr><td><code>kw_only</code></td><td><code>False</code></td><td><code>True</code> の場合、すべてのフィールドがキーワード引数専用になり、インスタンス化ではキーワード引数での指定が必要です。</td></tr><tr><td><code>slots</code></td><td><code>False</code></td><td><code>True</code> にすると <code>__slots__</code> が作成されます。</td></tr><tr><td><code>weakref_slot</code></td><td><code>False</code></td><td><code>True</code> にすると <code>__weakref__</code> が作成されます。</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">これまでの例で <code>init</code> 引数を指定しなくても <code>__init__()</code> が生成されていたのは、該当する <code>init</code> 引数のデフォルトが <code>True</code> であるためです。デフォルトで <code>False</code> になっている項目は、<code>@dataclass</code> の引数で <code>True</code> を指定することで有効にすることができます。</p>



<p class="wp-block-paragraph">必要に応じて上記の引数の設定を変更して利用してください。</p>



<h4 class="wp-block-heading jinr-heading d--bold">デフォルト値の割り当て</h4>



<p class="wp-block-paragraph"><code>@dataclass</code> デコレータを使ってデータクラスを定義する際に、デフォルト値を割り当てたい場合は、<span class="jinr-d--text-color d--marker1 d--bold"><code>field</code></span> 関数を使います。特に、ミュータブルな型のデフォルト値を安全に設定する場合には、<code>field</code> で <span class="jinr-d--text-color d--marker1 d--bold"><code>default_factory</code></span> 引数を使用します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from dataclasses import dataclass, field


@dataclass
class DataWithDefaults:
    """デフォルト値の設定"""

    immutable: str = field(default="")
    mutable: list = field(default_factory=list)

    def set_data(self, value):
        self.immutable = value
        self.mutable.append(value)


if __name__ == "__main__":
    test1 = DataWithDefaults()
    test2 = DataWithDefaults()

    test1.set_data("data1-1")
    test1.set_data("data1-2")
    test2.set_data("data2-1")

    # インスタンスの属性を確認
    print(test1.immutable)
    print(test1.mutable)
    print(test2.immutable)
    print(test2.mutable)</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
data1-2
['data1-1', 'data1-2']
data2-1
['data2-1'] </pre>



<p class="wp-block-paragraph">例では、<code>immutable</code> という変数のデフォルト値は <code>""</code> (空文字) としています。イミュータブルな型のデフォルト値は、<code>field</code> の <span class="jinr-d--text-color d--marker1 d--bold"><code>default</code></span> 引数 または 直接の割り当て（例: <code>immutable: str = ""</code>）で指定できます。</p>



<p class="wp-block-paragraph">一方で、ミュータブルな型のデフォルト値で「<code>mutable: list = []</code>」といった直接の割り当てはエラーとなります。具体的には、以下のように <code>ValueError</code> となります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ValueError: mutable default &lt;class 'list'> for field mutable is not allowed: use default_factory</pre>



<p class="wp-block-paragraph">この問題を回避するためには「<code>mutable: list = field(default_factory=list)</code>」というように <span class="jinr-d--text-color d--marker1 d--bold"><code>default_factory</code></span> 引数を使用します。</p>



<p class="wp-block-paragraph">Python を学習を進めている方は、関数やクラスのデフォルト引数としてミュータブルな型を使用する際のリスクについて学んだことがあるかと思います。複数のインスタンスが同じミュータブルなオブジェクトを共有してしまうと、予期しない問題が発生してしまうことがありますが、<code>@dataclass</code> の <code>field</code> を使用すれば、このリスクを回避しながらミュータブルなデフォルト値を安全に設定できます。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">Python でデータクラスを作成する際に便利な <span class="jinr-d--text-color d--marker1 d--bold"><code>@dataclass</code> デコレータの使い方</span>について解説しました。</p>



<p class="wp-block-paragraph"><code>@dataclass</code> デコレーターを使用すると、定型的なメソッド定義（ボイラープレートコード）を省略でき、データを表現するクラスの作成が非常に簡単になります。この記事では、簡単な例を使って <code>@dataclass</code> デコレータの使い方を紹介しました。</p>



<p class="wp-block-paragraph">データクラス定義の際は、<code>@dataclass</code> デコレータの使用を検討してみてください。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><code>dataclasses</code> の公式ドキュメントは<a href="https://docs.python.org/ja/3/library/dataclasses.html" target="_blank" rel="noreferrer noopener">こちら</a>を参照してください。</p>
</div>
		</div></section>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては <a href="https://github.com/nkhn37/python-tech-sample-source/tree/main/python-libraries/dataclasses" target="_blank" rel="noreferrer noopener">GitHub</a> にて公開しています。参考にしていただければと思います。</p>
</div></div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-dataclass-basics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-06-14 07:21:30 by W3 Total Cache
-->