Posted on:

05 Jul 2023

2

Easy example to understand!

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print("The animal speaks.")


# Child class inheriting from Animal
class Dog(Animal):
    def speak(self):
        print("Woof!")


# Child class inheriting from Animal
class Cat(Animal):
    def speak(self):
        print("Meow!")


# Creating instances of the classes
animal = Animal("Generic Animal")
dog = Dog("Buddy")
cat = Cat("Whiskers")


# Calling the speak() method on instances
animal.speak()  # Output: The animal speaks.
dog.speak()     # Output: Woof!
cat.speak()     # Output: Meow!

0 answers ( 0 marked as helpful)

Submit an answer