15
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

dataclassでクラス変数を記述する

Posted at

やり方

typingモジュールに、クラス変数であることを明示的に宣言する用の型が用意されているので、データクラスの作成時にクラス変数であることを明示して宣言すれば、__init__で用いられない。

from dataclasses import dataclass 
from typing import ClassVar

@dataclass
class TestClass:
    var1: ClassVar[str] = "class"
    var2: str = "instance"
$ TestClass(var1='var').var1
>>> TypeError: __init__() got an unexpected keyword argument 'var1'
$ TestClass(var2='var').var2
>>> 'var'

Reference

15
4
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
15
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?