[Python] Class inheritance in Python 3.7 dataclasses

Discussão em 'Python' iniciado por Stack, Janeiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    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 like the order of the arguments are botched by my current approach such that the bool parameter in the child class is passed before the other parameters. This is causing a type error.

    from dataclasses import dataclass

    @dataclass
    class Parent:
    name: str
    age: int
    ugly: bool = False

    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
    ugly: bool = True


    jack = Parent('jack snr', 32, ugly=True)
    jack_son = Child('jack jnr', 12, school = 'havard', ugly=True)

    jack.print_id()
    jack_son.print_id()


    When I run this code I get this TypeError:

    TypeError: non-default argument 'school' follows default argument


    How do I fix this?

    Continue reading...

Compartilhe esta Página