简体   繁体   中英

Python dataclasses inheritance part of attributes from parent dataclass

I constructed multiple base dataclass . Now I want to construct a child dataclass inheriting from these base classes, but may inherit part of attributes defined in some base classes. Examples can be:

import dataclasses

@dataclasses.dataclass
class A:
    a: int = None
    b: float = None
    c: str = None

@dataclasses.dataclass
class B:
    d: int = None
    b: float = 3.5

@dataclasses.dataclass
class C:
    e: int = None
    f: float = 3.5
    g: int = None

@dataclasses.dataclass
class D(A, B):
    def __post_init__(self):
        for _field, _field_property in C.__dataclass_fields__.items():
            if _field != "g":
                setattr(self, _field, _field_property.default)

Namely, I want to construct a child class D inheriting A and B , and attributes in C except g . Checking the child class D

>>> D.__dataclass_fields__.keys() # got dict_keys(['d', 'b', 'a', 'c'])
>>> d = D(a=4, b=2, c=5, d=3.4, e=2.1, g=55)
Traceback (most recent call last):
  File "<pyshell#77>", line 1, in <module>
    d = D(a=4, b=2, c=5, d=3.4, e=2.1, g=55)
TypeError: __init__() got an unexpected keyword argument 'e'

And

>>> D.__dict__.keys()
dict_keys(['__module__', '__post_init__', '__doc__', '__dataclass_params__', '__dataclass_fields__', '__init__', '__repr__', '__eq__', '__hash__'])

When I changed __post_init__ to __init__ and using super().__init__() for the inheritance, still can't the attributes from class C and lose the advantage of dataclass , ie,

>>> @dataclasses.dataclass
class D(A, B):
    def __init__(self):
        super().__init__()
        for _field, _field_property in C.__dataclass_fields__.items():
            if _field != "g":
                setattr(self, _field, _field_property.default)

And run

>>> d = D(a=4, b=2, c=5, d=3.4, e=2.1, g=55)
Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    d = D(a=4, b=2, c=5, d=3.4, e=2.1, g=55)
TypeError: __init__() got an unexpected keyword argument 'a'

What should I do?

Similar as what proposed by @GiacomoAlzetta, I suddenly come out that idea using dataclasses.make_dataclass , ie, generate a copy of C but excluding attribute g , ie,

<<< C_part = dataclasses.make_dataclass("C_part", [(_field, _field_property.type, _field_property.default) for _field, _field_property in C.__dataclass_fields__.items() if _field != "g"])

Thus I have

>>> C_part.__dataclass_fields__.keys()  # dict_keys(['e', 'f'])

Then the D can be obtained by

>>> @dataclasses.dataclass
class D(A, B, C_part):
    pass

>>> d = D(a=4, b=2, c=5, d=3.4, e=2.1, f=55)
>>> d
D(e=2.1, f=55, d=3.4, b=2, a=4, c=5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM