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
- 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.
- 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.
- An object of the Cat class is created with the name “Whiskers”, color “Gray”, breed “Persian”, and weight 15.
- 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.
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 Cat(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 Cat class
cat = Cat("Whiskers", "Gray", "Persian", 15)
cat.print_details()
Output:
Name: Whiskers
Color: Gray
Breed: Persian
Weight: 15
Related Articles
Create a Python class called BankAccount with attributes account_number and balance.
Create a Python class called SavingsAccount that inherits from the BankAccount class.
Create a Python class called CheckingAccount that inherits from the BankAccount class.
Create a Python class called Car with attributes make, model, and year.
Create a Python class called ElectricCar that inherits from the Car class.
Create a Python class called StudentRecord with attributes name, age, and grades.