Python Object-Oriented Python Inheritance Super!

Jason Smith
Jason Smith
5,073 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
MOD
Alex Koumparos
Python Web Development Treehouse Moderator 32,453 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
5,073 Points

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