Inheritance in Python
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.
Syntax
The syntax for a class B
to inherit a parent class A
is
class A:
pass
class B(A):
pass
Please observe the syntax: ChildClassName(ParentClassName)
.
Example
In this example, we define three classes: Animal
, Dog
, and Cat
.
Animal is parent class.
Dog
and Cat
are child classes of Animal
class.
The object of Dog
and Cat
classes can access the properties and methods of the Animal
class.
Python Program
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()
Output
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 methodspeak()
, and a methodrun()
. - The child classes
Dog
, andCat
, that inheritedAnimal
class, have access to the name property, and the methodsspeak()
andrun()
of theAnimal
class. - The two child classes have overridden the
speak()
method of parent class. Whenspeak()
method is called on any of the objects of child classes, then the method defined in the respective child classes is executed. The linedog.speak()
executes the method in the child classDog
. dog.run()
executes the method in parent classAnimal
, because the child class object can access the method in parent classAnimal
, and there is norun()
method in the child classDog
.
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.
Summary
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.