how are you, people? I am facing this problem: I want to get all methods and attributes of 2 classes like the example below
class Person1:
def __init__(self) -> None:
self.john_name = "John"
self.john_age = 36
def get_name_john(self) -> str:
return self.john_name
def get_age_john(self) -> int:
return self.john_age
class Person2:
def __init__(self) -> None:
self.ted_name = "Ted"
self.ted_age = 32
def get_name_ted(self) -> str:
return self.ted_name
def get_age_ted(self) -> int:
return self.ted_age
class Student(Person1, Person2):
def __init__(self) -> None:
super().__init__()
print(self.john_age)
print(self.ted_age)
print(self.get_name_john())
print(self.get_name_ted())
print(self.get_age_john())
print(self.get_age_ted())
student = Student()
But when I do this I can't access anything from Person2. Maybe someone can help me with it? Thank you for your attention.
1 Answer 1
You need to add super().__init__() to Person1 and Person2 as well. This is because of Method Resolution Order (MRO).
When __init__() is called in the Student class, the order at which to resolve __init__() is as follows:
Student -> Person1 -> Person2
Because __init__() is only called once, you would only be able to access Person1 which is one down the hierarchy.
After adding super().__init__() to both Person1 and Person2:
class Person1:
def __init__(self) -> None:
self.john_name = "John"
self.john_age = 36
super().__init__()
def get_name_john(self) -> str:
return self.john_name
def get_age_john(self) -> int:
return self.john_age
class Person2:
def __init__(self) -> None:
self.ted_name = "Ted"
self.ted_age = 32
super().__init__()
def get_name_ted(self) -> str:
return self.ted_name
def get_age_ted(self) -> int:
return self.ted_age
class Student(Person1, Person2):
def __init__(self) -> None:
super().__init__()
print(self.john_age)
print(self.ted_age)
print(self.get_name_john())
print(self.get_name_ted())
print(self.get_age_john())
print(self.get_age_ted())
The code now works.
3 Comments
super().function_name(). If that function exists in multiple parent classes, MRO will also apply, the same way it does here with __init__(). To change the order of MRO, you can simply change the order of the parent classes. For example you can swap the two classes around in Student(Person1, Person2), so that it would become Student(Person2, Person1), then the order of MRO would become Student -> Person2 -> Person1.
super()with multiple inheritance, then every class has to use it - even the base classes. The alternative would be to explicitly call both parent class's__init__methods fromStudent.__init__().