Python 2.x super __init__ inheritance doesn't work when parent doesn't inherit from object

cjm2671 picture cjm2671 · Apr 16, 2014 · Viewed 46.6k times · Source

I have the following Python 2.7 code:

class Frame:
    def __init__(self, image):
        self.image = image

class Eye(Frame):
    def __init__(self, image):
        super(Eye, self).__init__()
        self.some_other_defined_stuff()

I'm trying to extend the __init__() method so that when I instantiate an 'Eye' it does a bunch of other stuff (self.some_other_defined_stuff()), in addition to what Frame sets up. Frame.__init__() needs to run first.

I get the following error:

super(Eye, self).__init__()
TypeError: must be type, not classobj

Which I do not understand the logical cause of. Can someone explain please? I'm used to just typing 'super' in ruby.

Answer

Martijn Pieters picture Martijn Pieters · Apr 16, 2014

There are two errors here:

  1. super() only works for new-style classes; use object as a base class for Frame to make it use new-style semantics.

  2. You still need to call the overridden method with the right arguments; pass in image to the __init__ call.

So the correct code would be:

class Frame(object):
    def __init__(self, image):
        self.image = image

class Eye(Frame):
    def __init__(self, image):
        super(Eye, self).__init__(image)
        self.some_other_defined_stuff()