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!

Jason Smith
Jason Smith
7,439 Points

i've messed up somewhere...help!

I thought i was doing this right, but i keep getting 'bummer'!

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

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

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,862 Points

Hi Jason,

You have a couple of errors in your code. Let's work through it by letting Python tell us where the errors are:

When we run your code, this is what we get:

>>> inv = SortedInventory()
>>> inv.add_item('sword')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add_item() takes 1 positional argument but 2 were given

This is probably a familiar error message. We see it any time create an instance method and forget to define it with the self parameter.

Fix that and then run the code again. This time:

>>> inv = SortedInventory()
>>> inv.add_item('sword')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/User/inv.py", line 10, in add_item
    super().Inventory()
AttributeError: 'super' object has no attribute 'Inventory'

Remember, super() is a way of referring to the parent class. In the case of SortedInventory, the parent class is Inventory. This means that when you call super().Inventory() you are trying to call Inventory.Inventory(). What you really want to do is call the parent class's version of the same method you are in, which in your case is add_item.

Calling the parent's add_item method will put you in exactly the state you would be in if you were using the base Inventory class. So then, instead of appending the item to slots again, you need to implement the behaviour that makes SortedInventory different to Inventory (you need to make the inventory sorted).

Hope these hints point you in the right direction.

Cheers

Alex

Jason Smith
Jason Smith
7,439 Points

thanks a bunch! you pointed me in the right direction! have a BA!