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!

Sorted inventories should be just that: sorted. (Challange Task 3)

No idea why my code does not work, anyone can help? Not sure if I understand the question properly! ;(

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

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


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

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

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,624 Points

Hey Andreia,

You're kind of there, but I think you just got a bit side tracked. First, you are not asked to override the __init__, so that whole section in SortedInventory needs to be deleted.

Second, you are to override the add_item, which you have started correctly. But here the instructions explicitly say:

Use super() in it to make sure the item still gets added to the list.

So, you want to use the Parent method to add the items, therefore, you can't actually use append in the child class, as the parent class already has a method that does this, so you need to use super().add_item(item) to append the item in SortedInventory using the parent method of appending.

Finally your sorting method is a bit off. The challenge did not ask for a return so that needs to be deleted, And, you have the syntax a bit backward. You want to sort the items passed into the method, so you need self. And, you access the method using dot notation on the instance of slots.

This was a lot to take in, so I have included the corrected code (I usually don't) for you to have a look at and compare with what I've explained above:

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

I hope this helps to clear it up some. :)

Keep Coding! :dizzy:

Ahh, Silly me! that helps a lot! thanks a lot! ;)