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 |
|---|
| Python OOPS – Introduction |
| Python Classes and Objects |
| Python Object Methods |
| Python Inheritance |
| Polymorphism in Python |
| Python Access Modifiers |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| What is the use of self in Python? |
| What are public, protected and private attributes in Python? |
| What is the __init__() method in Python? |
| What is inheritance in Python? |