Why it is compulsory to give classname while using super() in Python

Question:

Possible Duplicate:
Why do I have to specify my own class when using super(), and is there a way to get around it?

I was reading this book – "Core Python Programming", and I really found it very nice I would say. But I got confused at a point while I was studying the topic Inheritance..

The book somewhere said that- we can use super() to invoke super class method which will find the base class method for us and also we don’t need to pass self explicitly, like we do without super..

Here’s the sample code: –

# Invoking super class method without super() .. Need to pass `self` as argument
class Child(Parent):
    def foo(self):
        Parent.foo(self)

# Invoking with super().
# No need to pass `self` as argument to foo()
class Child(Parent1, Parent2):
    def foo(self):
        super(Child, self).foo()
        print 'Hi, I am Child-foo()'

My Question is – why we have to pass the classname to super() call.. As the classname can be inferred from the class from which super is invoked..

So, since super() is invoked from
class Child, classname should be implicit there.. So why do we need that??

*EDIT: – Giving Child as a parameter to super() doesn’t make sense, because it doesn’t give any information.. We could have used super(self).. And the method would have been searched in the super classes in the order they are given inside parenthesis..

Asked By: Rohit Jain

||

Answers:

By providing the class name as first argument you provide redundant information. Yes. That’s a bit stupid* and that’s why the behavior of super is changed in Python 3 to:

super().__init__()

*With my answer I actually contradict the answer by John Carter. Only one of us is right, of course. I don’t want to offend him and others and I am happy to see a meaningful example where super(C, self).method(arg) is not actually used within class C :-).

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.