Hamy
Hamy

Reputation: 21542

Why do base classes in Python need to extend object?

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

Upvotes: 2

Views: 376

Answers (1)

jamylak
jamylak

Reputation: 133494

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.

Upvotes: 1

Related Questions