Class inheritance in Python 3.7 dataclasses

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

    You can use attributes with defaults in parent classes if you exclude them from the init function. If you need the possibility to override the default at init, extend the code with the answer of Praveen Kulkarni.

    from dataclasses import dataclass, field
    
    @dataclass
    class Parent:
        name: str
        age: int
        ugly: bool = field(default=False, init=False)
    
    @dataclass
    class Child(Parent):
        school: str
    
    jack = Parent('jack snr', 32)
    jack_son = Child('jack jnr', 12, school = 'havard')
    jack_son.ugly = True
    

提交回复
热议问题