4

in Python 2 there are two ways to call a method inherited from a parent class. With super where it is explicit that the methods is from the parent class and without super.

class Parent(object):
    def greet(self):
        print('Hello from Parent')

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()

    def hello(self):
        print('Hello from Child')
        self.greet()
        super(Child, self).greet()

child = Child()
child.hello()

Outputs:

Hello from Child
Hello from Parent
Hello from Parent

Which is the preferred one? I see the community suggests the invocation through super, but without super the call is much more concise.

The question is intended for Python 2 only.

1 Answer 1

6

In the context you've given, it doesn't make sense to call super(Child, self).greet() from inside Child.hello.

You should generally only use super to call the parent class' method of the same name as the overridden method you are inside.

So there's no need for super in Child.hello, since you're calling greet rather than the parent class's hello method.

Additionally, if there was a parent method Parent.hello then you might want to call that using super from within Child.hello. But that depends on the context and intention - e.g. if you wanted the child to slightly modify the parent's existing behaviour then it might make sense to use super, but if the child completely redefined the parent class behaviour, it might not make sense to call the parent's super method, if the result is just going to be discarded. It's generally better to be on the safe side and call the super class's methods though, as they may have important side effects that you want the child to preserve.

Also worth saying, this applies to both python 2 and 3. The only difference in Python 3 is that the super call is a bit nicer in python 3 because you don't need to pass the parent class and self to it as arguments. E.g. in py3 it's just super().greet() rather than super(Parent, self).greet().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.