Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Inheritance Super!

I need to create subclass but that give an error, so i don't know why...

Also i need a clear understanding for super class. I didn't get a good idea of that.

Thank you

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

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


class SortedInventory(Inventory):
    pass

2 Answers

Ari Misha
Ari Misha
19,274 Points

Sure thing! In simple words , you need "super()" when you need to call the reference to the super class. Lemme present ya a simple example:

class MyParentClass(object):
   def __init__(self):
      pass

class SubClass(MyParentClass):
   def __init__(self):
     super()

In the example above, class "SubClass" is extending the parent class "MyParentClass" , which in turn is extending "Object" class, which is built-in class in the python core. Class "SubClass" has an init method , which is pretty much overriding the init in the parent class "MyParentClass", and we called "super()". So yeah , super() in init of "SubClass" is referencing the init method of the parent class "MyParentClass" and when we'll initialize the init in "SubClass", super() will additionally run the init of the "MyParentClass". I hope it helped!

Regarding the challenge, your code should look like this:

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)

Thank you so much for explain so clear.

Ari Misha
Ari Misha
19,274 Points

Hiya Sepehr! I pasted your code in the editor and it gave me an error "Bummer! Try again", i think it must be indentation or something. I cant figure it out but your code seems to be alright. Try this:

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

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

class SortedInventory(Inventory):
    pass

yeah, it just reset my challenge and did it again then passed it.

but i don't understand what is super class in inheritance and why we should use.. i get after this challenge an error again can you help me in this challenge?