Python – Inheritance
In Python, inheritance is a way to create a new class that is a modified version of an existing class. Inheritance allows you to customise or extend the behavior of the class for your specific needs.
The existing class is called base class, parent class, or super class.
The new class is called extended class, child class, or sub class.
The syntax for a class
B to inherit a parent class
Run Code Online
class A: pass class B(A): pass
Please observe the syntax:
In this example, we define three classes:
Animal is parent class.
Cat are child classes of
The object of
Cat classes can access the properties and methods of the
Run Code Online
class Animal: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("Subclass must implement abstract method") def run(self): print(self.name, "is running.") class Dog(Animal): def speak(self): print(self.name, "says Woof Woof!") class Cat(Animal): def speak(self): print(self.name, "says Meow Meow!") dog = Dog("Pigo") cat = Cat("Keto") dog.speak() dog.run() cat.speak() cat.run()
Pigo says Woof Woof! Pigo is running. Keto says Meow Meow! Keto is running.
Now, let us discuss the example in detail.
- The parent class Animal has a property
name, an abstract method
speak(), and a method
- The child classes
Cat, that inherited
Animalclass, have access to the name property, and the methods
- The two child classes have overridden the
speak()method of parent class. When
speak()method is called on any of the objects of child classes, then the method defined in the respective child classes is executed. The line
dog.speak()executes the method in the child class
dog.run()executes the method in parent class
Animal, because the child class object can access the method in parent class
Animal, and there is no
run()method in the child class
Uses of Inheritance
Inheritance allows you to create classes that build upon the functionality of existing classes, while also providing the flexibility to customize or modify that functionality as needed.
By using inheritance, you can avoid duplicating code and make your code more modular and maintainable.
In this Python Classes and Objects tutorial, we learned about Inheritance in Python, and how to implement inheritance with classes, with the help of an example.