jojo
jojo

Reputation: 165

Using super() In class that inherits from object

I have seen a class like below:

from __future__ import print_function

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()

Why we may use super in a class that inherits from object? Is it the right approach?

Upvotes: 0

Views: 53

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125368

Yes, that's the right approach, because multiple inheritance makes it such that MyClass could end up in a different place in the MRO:

>>> class MyClass(object):
...     def __init__(self):
...         super(MyClass, self).__init__()
...
>>> class Foo(object):
...     def __init__(self):
...         print('Foo __init__!')
...         super(Foo, self).__init__()
...
>>> class Bar(MyClass, Foo):
...     pass
...
>>> Bar.__mro__
(<class '__main__.Bar'>, <class '__main__.MyClass'>, <class '__main__.Foo'>, <class 'object'>)

Here Bar inherits from both MyClass and Foo, placing Foo before object. Because, MyClass.__init__() is doing the right thing and passing on the __init__ chain via super(), Foo.__init__ is correctly called:

>>> Bar()
Foo __init__!
<__main__.Bar object at 0x107155da0>

Upvotes: 2

Related Questions