Sobes.tech
Junior — Middle

What should you know about inheritance in Python and what features does it include?

sobes.tech AI

Answer from AI

In Python, the inheritance mechanism supports several important features:

  • Multiple inheritance: a class can inherit from multiple base classes at once.
  • Method Resolution Order (MRO): determines the order in which methods and attributes are looked up during inheritance, especially important in multiple inheritance. Python uses the C3 linearization algorithm.
  • Calling base class methods: using super(), you can call a method from the parent class, which is particularly useful in multiple inheritance.
  • Dynamic typing and inheritance: Python allows changing attributes and methods of classes and objects at runtime.

Example of multiple inheritance and using super():

class A:
    def greet(self):
        print("Hello from A")

class B:
    def greet(self):
        print("Hello from B")

class C(A, B):
    def greet(self):
        super().greet()  # calls greet from A, as A is first in the inheritance list

c = C()
c.greet()  # Outputs: Hello from A

It is important to understand that the order of inheritance affects which method will be called when using super(). This helps in building flexible and extendable class hierarchies.