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

Understand super().

Hey guys,

Just wanted to throw a question out there regarding the super(). Now, i've read online and in my books at home everything there is on the super() and for the life of me either still don't know what it explicitly does nor do i understand when people explain it. I'm looking for an explanation you'd give to a GCSE student, even though I am old enough to understand big words it just seems to counter productive when trying to learn new things.

Does anyone have any real world examples or easier ways to explain it? for example:

super() let's you change things in the parent class. (It might not but im looking for an explanation like this) not: super() derives from the subclass of the objects mother's, brother's method instance where the instance is derived from the quantum of the class of 2020.

Hope someone can help, cheers in advance!

1 Answer

Steven Parker
Steven Parker
243,253 Points

You'll find "super" often used when a class overrides a method of the class it inherits from. Using "super" allows you to access the parent version even though the name is the same. For example:

class one():
    def msg(self):
        print("Message One")

class two(one):        # inherit from "one"
    def msg(self):     # but override "msg"
        print("Message Two")

    def msg1(self):
        super().msg()  # use parent "msg" instead of ours

x = two()

x.msg()                # prints "Message Two"
x.msg1()               # prints "Message One"

So could you say that because class Two is the child of class One (The parent), it inherits it's msg but because we define our own msg in the class it overrides it?

And msg1 is now choosing to use the superclass's version of .msg?

Steven Parker
Steven Parker
243,253 Points

That's right, having it's own "shadows" (hides) the one in the parent. But "super" allows you to access it.

Happy coding!