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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And to add confusion, Python3 no longer requires (object) - because all class are now 'new style'.
@hpaulj Good point but not that confusing cause it still works anyway if you do subclass it
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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.