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

47,409

Solution 1

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()

Solution 2

Frame must extend object because only the new style classes support super call you make in Eye like so:

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()
Share:
47,409

Related videos on Youtube

cjm2671
Author by

cjm2671

Founder of WikiJob, UK's largest graduate careers website. https://www.wikijob.co.uk. Founder of Linkly, https://linklyhq.com - click tracking software for marketers.

Updated on November 29, 2020

Comments

  • cjm2671
    cjm2671 over 3 years

    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.

    • That1Guy
      That1Guy about 10 years
      Frame must extend object. super will only work on new-style classes.
  • Evan Weissburg
    Evan Weissburg over 6 years
    To improve this answer, please check your formatting and provide an explanation for your code.
  • gented
    gented over 6 years
    Would the reference to object be redundant in Python > 3.X?
  • Martijn Pieters
    Martijn Pieters over 6 years
    @gented: yes, object as a base class is implied in Python 3 (as there are no old-style classes anymore).