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?
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?
Share Improve this question edited Mar 22 at 5:28 André 5903 silver badges18 bronze badges asked Mar 21 at 12:54 aleksandraleksandr 375 bronze badges 2 |2 Answers
Reset to default 2You are using kwargs
wrong. Add a key name during object creation and it will work:
emp = Employe('Head of IT', name='Chuck Norris', age=123)
emp.person_info()
emp.employe_info()
prints the output
I'm Chuck Norris and 123 y.o.
Head of IT
If you leave out any of Person
's arguments, it will fallback to the default.
From what I see from the code you are passing "*args" not the "kwargs". Thus you need to slightly modify the 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", *args, **kwargs):
super().__init__(*args, **kwargs)
self.position = position
def employe_info(self):
print(self.position)
Or alternatively call Employe
class with kwargs:
emp = Employe('a', name ='b', age = 'c')
Employe(position='a')
the instance will be created with defaulted parameters from the parent class – cards Commented Mar 21 at 13:08