Ask Your Question
1

How can we imitate or mimic calls to the parent class in Python?

asked 2021-08-07 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-11-21 06:00:00 +0000

djk gravatar image

In Python, we can mimic calls to the parent class using the super() function. This function allows us to invoke the method of the parent class from within a child class.

Here's an example of how we can use super() to mimic calls to the parent class:

class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child")

# Create an instance of Child and call its greet method
c = Child()
c.greet()

Here, we define two classes Parent and Child. The Child class inherits from the Parent class. The Parent class has a greet method that simply prints a greeting message. The Child class overrides the greet method and first calls the greet method of the parent class using super().greet(), and then prints its own greeting message.

When we create an instance of the Child class and call its greet method, we get the following output:

Hello from Parent
Hello from Child

So, we see that by using super() to invoke the method of the parent class, we can mimic calls to the parent class in Python.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-07 11:00:00 +0000

Seen: 11 times

Last updated: Nov 21 '22