Python Interview Questions

32 Questions
Python

Python

Web DevelopmentFrontendBackendData Science

Question 17

What is inheritance, and how is it implemented in Python?

Answer:

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (derived class or child class) to inherit attributes and methods from an existing class (base class or parent class). This promotes code reuse and establishes a hierarchical relationship between classes.

Key Concepts

  • Base Class (Parent Class): The class whose attributes and methods are inherited.
  • Derived Class (Child Class): The class that inherits attributes and methods from the base class.

Benefits of Inheritance

  • Reusability: Code can be reused across multiple classes, reducing redundancy.
  • Extensibility: New functionality can be added to the existing code without modifying it.
  • Maintainability: Code is easier to maintain and understand due to its organized structure.

Implementing Inheritance in Python

In Python, inheritance is implemented by defining a new class that includes the name of the base class in parentheses.

Basic Inheritance

Here's an example of basic inheritance:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Creating instances of Dog and Cat
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!

In this example:

  • Animal is the base class with an initializer method (__init__) and a placeholder method (speak).
  • Dog and Cat are derived classes that inherit from Animal and override the speak method.

Using super()

The super() function is used to call a method from the base class within the derived class. This is especially useful when you want to extend the functionality of the base class method.

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return f"{self.name} makes a sound."

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Call the initializer of the base class
        self.breed = breed
    
    def speak(self):
        return super().speak() + " Woof!"  # Extend the functionality of the base class method

dog = Dog("Buddy", "Golden Retriever")
print(dog.speak())  # Output: Buddy makes a sound. Woof!

In this example:

  • The Dog class uses super().__init__(name) to call the initializer of the Animal class.
  • The speak method in the Dog class extends the functionality of the speak method in the Animal class using super().speak().

Multiple Inheritance

Python supports multiple inheritance, where a class can inherit from more than one base class.

class A:
    def method_a(self):
        return "Method A"

class B:
    def method_b(self):
        return "Method B"

class C(A, B):
    pass

c = C()
print(c.method_a())  # Output: Method A
print(c.method_b())  # Output: Method B

In this example:

  • Class C inherits from both A and B, allowing it to access methods from both base classes.

Method Resolution Order (MRO)

In the case of multiple inheritance, Python uses the C3 linearization algorithm (also known as the method resolution order, or MRO) to determine the order in which base classes are searched when executing a method.

You can view the MRO of a class using the __mro__ attribute or the mro() method.

print(C.__mro__)
# Output: (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

print(C.mro())
# Output: [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]

Summary

  • Inheritance allows a new class (derived class) to inherit attributes and methods from an existing class (base class).
  • Base Class: The class whose attributes and methods are inherited.
  • Derived Class: The class that inherits from the base class.
  • super() Function: Used to call methods from the base class.
  • Multiple Inheritance: A class can inherit from multiple base classes.
  • Method Resolution Order (MRO): Determines the order in which base classes are searched for methods.

Inheritance is a powerful feature in Python that facilitates code reuse, extensibility, and maintainability by establishing relationships between classes.

Recent job openings