Python Object-Oriented Python Inheritance Super!

Nicolae Laurentiu
Nicolae Laurentiu
1,538 Points

I don't understand why do I have to use super() function. It is so confusing. Could anyone explain me in a more basic ?

No idea how to resolve the exercise. Please, I need help with the super() class. I don't understand it at all .

inventory.py
class Inventory:
    def __init__(self):
        self.slots = []

    def add_item(self, item):
        self.slots.append(item)

class SortedInventory(Inventory):
    def __init__(self, item):
        self.slots = []
        super().__init__()

    def add_item(item):       
        super().add_item(item)

2 Answers

Steven Parker
Steven Parker
174,023 Points

You might think of "super()" as meaning "use the one in the base class instead of my own".

For example, both classes shown here have a method called "add_item", but if you are writing code inside the "SortedInventory" class you don't want to call it's own method. By putting "super()" in front of "add_item()" you are calling the one in the "Inventory" class instead (the base or "parent" class).

You have actually done that part correctly in your challenge code, but there are two other issues preventing it from passing:

  • the instructions did not ask you to override the "__init__" method (you can remove that code)
  • the "add_item" method needs "self" as the first parameter
Chris Freeman
Chris Freeman
Treehouse Moderator 56,951 Points

Extending Steven Parker’s answer, when a class method is created with the same name as a method in one of its parent classes, this new method overrides the parent method thus blocking access to the parent method.

The use of super().__method_name__ allows you to bypass the name override by saying “skip the local name space and search the parent’s namespace for this method.”

The main use of super() is to extend the parent’s method of the same name. Note that the super() statement may be used at the beginning, end, or middle of a method so you can run the local method’s code after, before, or both, respectively, the parent’s method code.

Post back if you need more help. Good luck!!!

Nicolae Laurentiu
Nicolae Laurentiu
1,538 Points

I still get an error after modifying the code: What is the problem? I have tried the code in the python IDE and it worked.

class Inventory:
    def __init__(self):
        self.slots = []

    def add_item(self, item):
        self.slots.append(item)

class SortedInventory(Inventory):
    def add_item(self, item):
            super().add_item(item)

[MOD: added ```python formatting -cf]

Nicolae Laurentiu
Nicolae Laurentiu
1,538 Points

Thank you Chris. You are right.