Class inheritance in Python 3.7 dataclasses

前端 未结 8 745
离开以前
离开以前 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:41

    I came back to this question after discovering that dataclasses may be getting a decorator parameter that allows fields to be reordered. This is certainly a promising development, though development on this feature seems to have stalled somewhat.

    Right now, you can get this behaviour, plus some other niceties, by using dataclassy, my reimplementation of dataclasses that overcomes frustrations like this. Using from dataclassy in place of from dataclasses in the original example means it runs without errors.

    Using inspect to print the signature of Child makes what is going on clear; the result is (name: str, age: int, school: str, ugly: bool = True). Fields are always reordered so that fields with default values come after fields without them in the parameters to the initializer. Both lists (fields without defaults, and those with them) are still ordered in definition order.

    Coming face to face with this issue was one of the factors that prompted me to write a replacement for dataclasses. The workarounds detailed here, while helpful, require code to be contorted to such an extent that they completely negate the readability advantage dataclasses' naive approach (whereby field ordering is trivially predictable) offers.

提交回复
热议问题