Reputation: 81
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.
Upvotes: 0
Views: 179
Reputation: 181
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.
Upvotes: 1