48. Problem to create an inheritance example in Python

In this Python oops program, we will create an inheritance example in Python. Python class called Dog that inherits from the Animal class.

Inheritance example in Python

Steps to solve the program
  1. The Dog class extends the Animal class, which means it inherits the properties and methods of the Animal class.
  2. The Dog class has its own constructor method __init__ that takes four parameters: name, color, breed, and weight. It calls the constructor of the Animal class using super() to initialize the name and color properties inherited from the Animal class. It also initializes two additional properties: self.breed to store the breed of the dog and self.weight to store the weight of the dog.
  3. The Dog class overrides the print_details method inherited from the Animal class. It calls the print_details method of the Animal class using super().print_details() to print the name and color of the dog. Then, it prints the additional details: breed and weight.
  4. The code creates an object dog of the Dog class by calling its constructor with the arguments “Jelly”, “Golden”, “Golden Retriever”, and 25.
  5. The print_details method is called on the dog object to print the details of the dog, including the inherited name and color, as well as the breed and weight specific to the Dog class.
  6. Thus, we have created an inheritance example in Python.
				
					class Animal:
    def __init__(self, name, color):
        self.name = name
        self.color = color
    
    def print_details(self):
        print("Name:", self.name)
        print("Color:", self.color)

class Dog(Animal):
    def __init__(self, name, color, breed, weight):
        super().__init__(name, color)
        self.breed = breed
        self.weight = weight
    
    def print_details(self):
        super().print_details()
        print("Breed:", self.breed)
        print("Weight:", self.weight)

# Create an object of the Dog class
dog = Dog("Jelly", "Golden", "Golden Retriever", 25)
dog.print_details()
				
			

Output:

				
					Name: Jelly
Color: Golden
Breed: Golden Retriever
Weight: 25
				
			

Related Articles

Create a Python class called Animal with attributes name and color.

Leave a Comment