What is multiple inheritance in Python?
a) A class inheriting from only one base class
b) A class inheriting from multiple base classes
c) A class with multiple methods
d) A function returning multiple values
Answer:
b) A class inheriting from multiple base classes
Explanation:
Multiple inheritance in Python occurs when a class inherits from more than one base class. This allows the derived class to inherit attributes and methods from multiple classes.
class Parent1:
def greet(self):
print("Hello from Parent1")
class Parent2:
def greet(self):
print("Hello from Parent2")
class Child(Parent1, Parent2):
pass
# Creating an object of Child class
child = Child()
child.greet() # Output: Hello from Parent1 (depends on method resolution order)
In this example, the Child
class inherits from both Parent1
and Parent2
. If both parent classes have a method with the same name, the method resolution order (MRO) determines which method is called.
Multiple inheritance allows for greater flexibility in designing classes, but it can also lead to complexity and potential conflicts, so it should be used with care.