Python Multiple Inheritance

www.ig‮aeditfi‬.com

Multiple inheritance is a feature of object-oriented programming in Python that allows a subclass to inherit from multiple superclasses. This means that a subclass can have multiple parent classes and can inherit attributes and methods from all of them.

Here's an example of how to define a class that inherits from multiple superclasses in Python:

class A:
    def method(self):
        print("Method of A called")

class B:
    def method(self):
        print("Method of B called")

class C(A, B):
    pass

In this example, we've defined two superclasses A and B, each with their own implementation of a method function. We've then defined a subclass C that inherits from both A and B. We've left C empty, so it doesn't have any attributes or methods of its own.

We can create an object of the C class and call its method function:

c = C()
c.method()

When we call c.method(), Python looks for a method function in C. Since C doesn't have its own implementation of method, Python looks for the function in the superclasses of C in the order they were listed in the definition of C. In this case, Python finds method in A before B, so it calls the method function of A. The output will be:

Method of A called

Multiple inheritance can be a powerful tool for code reuse, but it can also lead to some complexity and ambiguity. When two or more superclasses define the same method or attribute, it's up to the subclass to decide which implementation to use. It's important to be careful when using multiple inheritance and to ensure that the design is well thought out and organized.