Sobes.tech
Junior — Middle

Can you explain how inheritance is implemented and how it functions in the Python language?

sobes.tech AI

Answer from AI

In Python, inheritance is implemented by specifying base classes in the class definition. The derived class inherits all attributes and methods of the base class and can override them or add new ones.

Example of simple inheritance:

class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):
        print("Bark")

dog = Dog()
dog.speak()  # Outputs: Bark

Python supports multiple inheritance, where a class can inherit from multiple base classes:

class Flyer:
    def fly(self):
        print("I can fly")

class Swimmer:
    def swim(self):
        print("I can swim")

class Duck(Flyer, Swimmer):
    pass

duck = Duck()
duck.fly()  # I can fly
duck.swim() # I can swim

The method resolution order (MRO) determines the order in which base classes are searched when executing a method.

Thus, inheritance in Python is a flexible way to extend and override class functionality.