views:

2711

answers:

3

Hi,

I was wondering if anyone could explain to me the difference between doing

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

and this

class Child(SomeBaseClass):
    def __init__(self):
     SomeBaseClass.__init__(self)

I've seen 'super' being used quite alot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation ?

Any thoughts on this would be greatly appreciated.

thanks

babak

+15  A: 

The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.

However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.

John Millikin
+9  A: 

John is absolutely right about the benefits/uses of super.

Here is a good article on the pitfalls of super(): Python's Super Considered Harmful. Despite the name, it is not an inflammatory article, and carefully describes the goals and uses of super() as well as the issues.

Dan
+4  A: 

Doesn't all of this assume that the base class is inherited from object?

class A:
    def __init__(self):
        print "A.__init__()"

class B(A):
    def __init__(self):
        print "B.__init__()"
        super(B, self).__init__()

Will not work. class A must be derived from object, i.e: class A(object)

mhawke
in 3.0, it will always be inherited from object
Corey Goldberg
Yes, it's true... `super()` only works on "new-style" classes descended from `object`, since their method-resolution order is more complex than old-style classes.
Dan