Class inheritance in Python 3.7 dataclasses

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

    The approach below deals with this problem while using pure python dataclasses and without much boilerplate code.

    The ugly_init: dataclasses.InitVar[bool] serves as a pseudo-field just to help us do initialization and will be lost once the instance is created. While ugly: bool = field(init=False) is an instance member which will not be initialized by __init__ method but can be alternatively initialized using __post_init__ method (you can find more here.).

    from dataclasses import dataclass, field
    
    @dataclass
    class Parent:
        name: str
        age: int
        ugly: bool = field(init=False)
        ugly_init: dataclasses.InitVar[bool]
    
        def __post_init__(self, ugly_init: bool):
            self.ugly = ugly_init
    
        def print_name(self):
            print(self.name)
    
        def print_age(self):
            print(self.age)
    
        def print_id(self):
            print(f'The Name is {self.name} and {self.name} is {self.age} year old')
    
    @dataclass
    class Child(Parent):
        school: str
    
    jack = Parent('jack snr', 32, ugly_init=True)
    jack_son = Child('jack jnr', 12, school='havard', ugly_init=True)
    
    jack.print_id()
    jack_son.print_id()
    

提交回复
热议问题