Inheritance is a mechanism of inheriting methods and properties of one class to another.
A class from which properties and methods are inherited to another class is called a Parent class
A class which inherits properties and methods from a Parent class is called its Child class.
To see inheritance example, we need to create a parent class and a child class.
To create a parent class, you just need to create a class because any class can be a parent class:
class Animal: def __init__(self, name, color): self.name = name self.color = color def print_name(self): print(self.name) def print_color(self): print(self.color)
To create a child class you need to pass the parent class as a parameter of the child class as shown in the example below:
class Dog(Animal): def print_weight(self, weight): print(self.weight)
Next, create an object of the child class and you can called its parent's methods as shown in the example below:
dog = Dog("Tommy","Black") dog.print_name() dog.print_color() dog.print_weight("160 pounds")