on Sep 3rd, 2008How super() should be used when calling a parent’s method

Edit: You learn something new every day, it turns I was the disillusioned one, the correct way to call super is actually this:

class Demo(object):
        def __init__(self):
                print "From Demo"

class Test(Demo):
        def __init__(self):
                super(Test, self).__init__()
                print "From Test"
o
o = Test()

Because if you do this:

class Demo(object):
        def __init__(self):
                print "From Demo"

class Test(Demo):
        def __init__(self):
                super(self.__class__, self).__init__()
                print "From Test"

o = Test()

More then one level of inheritance will make it go into an infinite loop, thanks to Manuel and Malcom that pointed it out to me.

5 Responses to “How super() should be used when calling a parent’s method”

  1. Malcolm Tredinnickon 03 Sep 2008 at 5:23 pm

    This won’t work. The relevant issue is that since “self” is always an instance of the child class, even when calling methods defined on the ancestor classes, self.__class__ will always be the child class. So, in your example, even in Demo, self.__class__ will be Test and you want to be calling super(Demo) from Demo, not super(Test).

  2. Fredrik Holmströmon 03 Sep 2008 at 7:10 pm

    Actually, you’re wrong. I wan’t to be calling super(Test, self).__init__() from Test, which is what I’m doing, take this example:
    class Demo(object):
    ….def __init__(self):
    ……..print “From Demo”

    class Test(Demo):
    ….def __init__(self):
    ……..if (Test is self.__class__):
    …………print “Test is the same as self.__class__”
    ……..
    ……..super(self.__class__, self).__init__()
    ……..super(Test, self).__init__() # Will print the same thing as the line above
    ……..super(Demo, self).__init__() # Wont print anything since it’s calling object.__init__()
    ……..
    ……..print “From Test”

    o = Test()

  3. manuelgon 03 Sep 2008 at 7:53 pm

    Code demonstrating error pointed out by Malcolm Tredinnick:

    http://python.pastebin.com/f32ac2a82

    Basically:

    super(self.__class__, self)

    is never the correct way to perform a “super” call — it will cause
    a recursion limit runtime error.

    Mistakes like this are part of the reason for PEP 3135 — New Super

    http://www.python.org/dev/peps/pep-3135/

    Also see Michele Simionato’s three part write-up on the nuances of Python’s “super”

    http://www.artima.com/weblogs/viewpost.jsp?thread=236275

  4. Mikeon 03 Sep 2008 at 7:55 pm

    Is there anything wrong with this?

    class Test(Demo):
    ….def __init__(self):
    ……..Demo.__init__(self)
    ……..print “From Test”

  5. Fredrik Holmströmon 03 Sep 2008 at 8:25 pm

    Malcom and Manuel, you’re right guys - I was severely mistaken and have edited the post to reflect the correct way to call super().

Trackback URI | Comments RSS

Leave a Reply