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..
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.
Essentially, the super function can be used to gain access to inherited methods – from a parent or sibling class – that has been overwritten in a class object. Or, as the official Python documentation says: “[Super is used to] return a proxy object that delegates method calls to a parent or sibling class of type.
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).
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.
*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
:-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With