Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Eldin Guzin
Eldin Guzin
6,010 Points

I have a question about super()

I don't quite get why do we use this... Can someone explain to me through this example below,why did we need to use super()

class Sneaky: sneaky = True

def __init__(self, sneaky=True, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.sneaky = sneaky

Thanks in advance !

1 Answer

Steven Parker
Steven Parker
243,266 Points

Since you are defining a method named "__init__", if you then call it directly it would be calling itself, which would start a "recursion loop" and crash the program.

But by using "super" you can call the method of the same name in the parent class instead, which causes no loop.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,468 Points

To slice it a bit finer:

Running __init__(*args, **kwargs) yields the error the name __init__ is not defined.

Using self.__init__(*args, **kwargs) would raise the error: RecursionError: maximum recursion depth exceeded while calling a Python object

Eldin Guzin
Eldin Guzin
6,010 Points

Thanks! That cleared up some things