29. Problem to show inheritance of classes in Python

In this Python oops program, we will create classes to show inheritance of classes in Python. This code demonstrates the concept of inheritance of classes in Python.

Inheritance of classes in Python

Steps to solve the program
  1. The Animal class has a constructor method __init__ that takes two parameters, name and color. Inside the constructor, the values of name and color are assigned to the instance variables self.name and self.color, respectively. This class also defines a method print_details that prints the name and color of the animal.
  2. The Cat class is a subclass of Animal, as indicated by (Animal) in its class definition. It adds two additional attributes, breed and weight, which represent the cat’s breed and weight, respectively. The class overrides the print_details method inherited from Animal and extends it by calling the print_details method of the superclass using super().print_details(), and then printing the cat’s breed and weight.
  3. An object of the Cat class is created with the name “Whiskers”, color “Gray”, breed “Persian”, and weight 15.
  4. The cat variable now refers to this object. The print_details method is then called on the cat object, which executes the overridden print_details method in the Cat class. This method first calls the print_details method of the Animal class using super().print_details() to print the animal’s name and color, and then prints the cat’s breed and weight.

Output:

Related Articles

Create a Python class called Student that inherits from the Person class.

Create a Python class called BankAccount with attributes account_number and balance.

Leave a Comment