[Python] How to implement inheritance of default attribute values

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to inherit instance's attributes. It works. But if i pass attributes values to the instance initialization, there is an error.

    My code:

    class Person:
    def __init__(self, name="Duck", age=2):
    self.__name = name
    self.__age = age


    def person_info(self):
    print(f"I'm {self.__name} and {self.__age} y.o.")


    class Employe(Person):
    def __init__(self, position="boss", **kwargs):
    super().__init__(**kwargs)
    self.position = position

    def employe_info(self):
    print(self.position)


    If i pass the attributes:

    emp = Employe('a', 'b', 'c')


    There is an error:

    line 19, in <module>
    TypeError: Employe.__init__() takes from 1 to 2 positional arguments but 4 were given


    How to implement this kind of inheritance to have default atr values from parent class and to be possible to pass atr values during child initiation?

    Continue reading...

Compartilhe esta Página