Class inheritance in Python 3.7 dataclasses

前端 未结 8 765
离开以前
离开以前 2020-11-28 22:12

I\'m currently trying my hands on the new dataclass constructions introduced in Python 3.7. I am currently stuck on trying to do some inheritance of a parent class. It looks

8条回答
  •  盖世英雄少女心
    2020-11-28 22:45

    You're seeing this error because an argument without a default value is being added after an argument with a default value. The insertion order of inherited fields into the dataclass is the reverse of Method Resolution Order, which means that the Parent fields come first, even if they are over written later by their children.

    An example from PEP-557 - Data Classes:

    @dataclass
    class Base:
        x: Any = 15.0
        y: int = 0
    
    @dataclass
    class C(Base):
        z: int = 10
        x: int = 15
    

    The final list of fields is, in order,x, y, z. The final type of x is int, as specified in class C.

    Unfortunately, I don't think there's any way around this. My understanding is that if the parent class has a default argument, then no child class can have non-default arguments.

提交回复
热议问题