具有多重继承(mixin)和混合默认选项的Python @dataclass

时间:2019-01-05 11:51:37

标签: python python-3.x mixins python-dataclasses

我正在尝试创建一个由继承的数据类组成的Python 3.7数据类:

from dataclasses import dataclass

@dataclass
class A:
    title: str
    synopsis: str = "A book"

@dataclass
class B:
    id: str
    description: str = "A short book about something"

@dataclass()
class C(A, B):
    provider: str

c = C(title="Trainspotting")

这将引发以下异常:

Traceback (most recent call last):
File "tests/test.py", line 14, in <module>
    class C(A, B):
File "lib/python3.7/dataclasses.py", line 958, in wrap
    return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
File "lib/python3.7/dataclasses.py", line 879, in _process_class
    else 'self',
File "lib/python3.7/dataclasses.py", line 466, in _init_fn
    raise TypeError(f'non-default argument {f.name!r} '

TypeError: non-default argument 'title' follows default argument

似乎Python的@dataclass分辨率在通过MRO进行反向操作时并未对齐所有父级的默认和非默认选项。有办法解决吗?

0 个答案:

没有答案