Hi Guys, welcome to my blog in this article you will learn about how to Write A Program To Implement The Concept Of Inheritance In Python
Title :
Write A Program To Implement The Concept Of Inheritance In Python
Description :
Hey guys in this article you will learn How to Define a generic class and then inherit a new class from the generic class.
Define an animal class having name and age initialize it in the constructor, also define a class Member function named as speak and print the generic message the animal speaks.
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("This animal speaks.")
Now take another class named as dog and inherit the animal class by passing animal class, use the default Constructor and initialize the name age and breed and use the super function to call the main generic class constructor. Similarly take a cat class and inherit the animal class and also define the default constructor by calling super function and also define speak function. The dog class contains extra variable named as breed, he the CAT class contains extra variable named as color
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self):
print(self.name, "Says Bow Bow!")
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
print(self.name, "Says Meow!")
In the main program take two objects dog and cat and instantiate dog and cat class by passing name age and breed for dog, past name is and color for cat. Now using the object called the member functions speak to print how dogs speak and cats speak.
dog = Dog("Shera", 3, "Labrador")
cat = Cat("Billa", 2, "Bark Brown")
dog.speak()
cat.speak()
Complete Python Code :
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("This animal speaks.")
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self):
print(self.name, "Says Bow Bow!")
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
print(self.name, "Says Meow!")
dog = Dog("Shera", 3, "Labrador")
cat = Cat("Billa", 2, "Dark Brown")
dog.speak()
cat.speak()
Output :
Shera Says Bow Bow!
Billa Says Meow!
Output :
Conclusion :
The above Python program Defines a generic class name for an animal and then defines a dog and cat class that inherits the animal class.
The dog class has a new member variable named as breed, the CAT class has a new member variable named as color.
The dog class overrides the speak function and the cat class overrides the speak function differently as shown above.
Comment it down below if you have any suggestions to improve the above Python program
0 Comments