Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
108 views
in Python by (178k points)
How do you override a method in a child class?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

You can override a method in a child class by defining a new method with the same name in the child class. When an instance of the child class calls the overridden method, the child class's version of the method will be called instead of the parent class's version.

Here's an example:

class Animal:
    def make_sound(self):
        print("Generic animal sound")

class Cat(Animal):
    def make_sound(self):
        print("Meow")

class Dog(Animal):
    def make_sound(self):
        print("Woof")

my_animal = Animal()
my_animal.make_sound()  # Output: "Generic animal sound"

my_cat = Cat()
my_cat.make_sound()  # Output: "Meow"

my_dog = Dog()
my_dog.make_sound()  # Output: "Woof"
 

In this example, we define a parent class Animal with a method make_sound() that prints a generic animal sound. We then define two child classes Cat and Dog, each of which overrides the make_sound() method with its own implementation.

When we create an instance of Cat or Dog and call the make_sound() method, the appropriate version of the method is called based on the instance's class. If we create an instance of Animal and call make_sound(), the parent class's version of the method is called.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...