Sobes.tech
Junior — Middle

How is inheritance implemented in the Python programming language?

sobes.tech AI

Answer from AI

In Python, inheritance is implemented through defining a subclass, which is specified in parentheses after the class name. The subclass inherits all attributes and methods of the parent class, allowing code reuse and functionality extension.

Example of simple inheritance:

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

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


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

Here, the Dog class inherits from Animal and overrides the speak method. Python supports multiple inheritance, where a class can inherit from multiple parent classes, for example:

class A:
    pass

class B:
    pass

class C(A, B):
    pass

Inheritance in Python is a powerful tool for organizing code and creating class hierarchies.