2

I'm looking for a clear explanation of why my base classes must extend object if I want to use super

# Without extending object, this code will fail with 
# TypeError: must be type, not classobj
class A(object):
  def __init__(self):
    print "Called A.__init__"

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

AChild()

This works as expected, but if you remove object it throws the exception mentioned. I'm using Python 2.7.8. Feel free to link me to any related questions, but I didn't find a good answer with a quick search

Hamy
  • 20,662
  • 15
  • 74
  • 102

1 Answers1

1

It's because by extending object you are using new style classes which are required to support the use of super, which was added alongside the introduction of new style classes to Python.

According to the information in this answer, old style classes had a simple depth-first method resolution order so there was no need for this function, and thats probably why it wasn t included then. However upon adding multiple inheritance, super is now the recommended way to call a superclass because of the more complicated MRO.

Community
  • 1
  • 1
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • And to add confusion, Python3 no longer requires `(object)` - because all class are now 'new style'. – hpaulj Dec 10 '14 at 04:53
  • @hpaulj Good point but not that confusing cause it still works anyway if you do subclass it – jamylak Dec 10 '14 at 04:55
  • `super` is not just a new way to access a super class. It's meant for implementing cooperative inheritance, meaning all classes in the hierarchy where `super` is used must be written to support the use of `super` in any ancester/class in the hierarchy. It's important to understand the implications of using `super` before using it. – chepner Dec 10 '14 at 05:29
  • @chepner I was talking about why there was not an equivalent `super` for old style classes beforehand and maybe that could have predicted these additions to the language and been forward compatible. – jamylak Dec 10 '14 at 05:48