What is inheritance in Python?

Inheritance lets a new class (child) take the attributes and methods of an existing class (parent). It helps to reuse code, and the child can also change or add its own behaviour.

class Animal:
    def speak(self):
        print("Some sound")

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

class Cat(Animal):
    pass

Dog().speak()
Cat().speak()

Output:

Tutorials Class - Output Window

Bark
Some sound

Dog replaces (overrides) the speak() method, while Cat uses the one from Animal. Use super() to call a method of the parent class. Python supports single, multiple, multilevel, hierarchical and hybrid inheritance. See Python OOPS Introduction.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.