avatarLaxfed Paulacy

Summarize

PYTHON — Adding an Extra Method to Extend Child Class in Python

Computer science is no more about computers than astronomy is about telescopes. — Edsger W. Dijkstra

In this lesson, we will learn how to add an extra method to extend a child class in Python. We will explore a farm model with different animals and their behaviors. Specifically, we will add a .fetch() method to the Dog class, which is not present in the parent class or other child classes such as Pig or Sheep.

Let’s dive into the code and see how we can achieve this:

import time

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

    def talk(self):
        pass  # Let's implement this method in the child classes

class Dog(Animal):
    def talk(self):
        print(f"{self.name} says Woof!")

    def fetch(self, thing):
        print(f"{self.name} dashes after the {thing}...")
        time.sleep(0.5)  # Wait for half a second
        print(f"{self.name} returns the {thing} to you")
        return thing

In the above code, we have defined a base class Animal and a child class Dog. The Dog class has a method fetch which is not present in the parent class Animal. The fetch method simulates a dog fetching an object and returning it.

To test the functionality of the fetch method, we can create an instance of the Dog class and invoke the fetch method:

# Create a Dog instance
my_dog = Dog("Buddy")

# Make the dog fetch a ball
returned_item = my_dog.fetch("ball")
print(f"The {returned_item} was fetched by {my_dog.name}")

When we run the above code, we will see the output as follows:

Buddy dashes after the ball...
Buddy returns the ball to you
The ball was fetched by Buddy

This demonstrates how we can extend a child class in Python by adding an extra method that is specific to that child class. This is a powerful feature of object-oriented programming that allows for flexibility and customization in defining the behavior of different classes within a hierarchy.

In conclusion, adding extra methods to extend child classes in Python provides a way to introduce specific behaviors to individual classes within a class hierarchy. This allows for tailored functionality and behavior for different objects within a system, enhancing the flexibility and reusability of the code.

Class
Adding
ChatGPT
Child
Method
Recommended from ReadMedium