2
6

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 3 years have passed since last update.

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

Last updated at Posted at 2020-01-24

各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'>
2
6
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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?