That's a great idea! Customizing a child class in multiple inheritance allows you to combine behaviors from both parents or completely override them.
Here are a few ways you can customize Child_AB in your multiple_inheritance.py file:
1. Override and use super()
You can make Child_AB do something unique and then call the parent's logic. Because ParentA is first in the inheritance list, super() will look there first.
class Child_AB(ParentA, ParentB):
def speak(self):
print("Child_AB is starting to speak...")
super().speak() # This calls ParentA's speak()
2. Specifically call a "hidden" parent method
Since ParentA comes first, ParentB's common_method is usually hidden. You can explicitly call it if you want to use both:
class Child_AB(ParentA, ParentB):
def common_method(self):
print("Child_AB is combining both parents' methods:")
ParentA.common_method(self) # Call A specifically
ParentB.common_method(self) # Call B specifically
3. Add a new specialized method
You can also add functionality that neither parent has:
class Child_AB(ParentA, ParentB):
def introduce(self):
print("I am a specialized child of both A and B!")
Updated script example
Try updating your Child_AB class and the if __name__ == "__main__": block like this:
class Child_AB(ParentA, ParentB):
def speak(self):
print("Child_AB is clearing its throat...")
super().speak()
def common_method(self):
print("--- Custom Logic in Child_AB ---")
ParentB.common_method(self) # We chose to use ParentB's version here!
# In the __main__ section:
if __name__ == "__main__":
child1 = Child_AB()
child1.speak()
child1.common_method()
Why this is useful:
- Method Chaining: Using
super()allows you to add "setup" code before the parent logic runs. - Selection: In multiple inheritance, you can pick and choose which parent's logic to use for specific methods, giving you full control over the class behavior.
Give one of these a try in your editor and run the script again! How does the output change?