Help us understand the problem. What is going on with this article?

pythonのdataclassで後ろに継承したい

各dataclassで共通のフィールドがほしい、でもデフォルトの値を付けたいから普通に継承すると前にこれがついてtypeerror。つらいさんなのだ

だめ

from dataclasses import dataclass

@dataclass
class Base:
   base: int = 10

@dataclass
class Extend(Base):
    extend: int

typeerrorです

あと、@dataclassしていないclassを継承しても継承元のフィールドは(__init__には)継承しないみたい。

正直読みにくいけどまあ解決

デコレータを書きます

from dataclasses import dataclass

def add(c):
    @dataclass
    class wrap(c):
        added: int = 10
    return wrap

@add
@dataclass
class DataClass:
    field: str

欠点としては、インタプリタで名前じゃなくて<locals>.wrapになることですね

>> DataClass
<class '__main__.add.<locals>.wrap'>

追記

どうやらclassの名前は__qualname__にあるらしい。

def add(c):
    @dataclass
    class wrap(c):
        added: int = 10
        __qualname__ = c.__qualname__
    return wrap
>> DataClass
<class '__main__.DataClass'>
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした