i don't understand super(), what is it doing exactly, and it seems like im repeating myself when writing def add_item inside class sortedinventory why are we not using item in this challenge and when should i use it ?
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)
Chris FreemanTreehouse Moderator 56,641 Points
Good question! The process for calling a class instance method goes as follows:
Say you are looking for the
add_item method in
- look in the method
add_itemin the name space of the local
- If not found, look in the each parent class listed in the inheritance list. In this case,
But what if you want the behavior of
Inventory.add_item but want a bit more in the local version. You could do one of two things:
SortedInventorythen make the changes you need. This isn't Pythonic because if the original method in
Inventorywas changed then the changes wouldn't be reflected in the copied method.
- some how still be able to call both the local and the inherited methods. This is where
SortedInventory.add_item exists, the method
Inventory.add_item cannot be directly accessed from the local instance. The
super() function provides the solution. Its basic function is to shift execution to the parent's version of the method, then return to execution in the local version. Without the
super() only the local method would execute.
Looking at the point you are at in your code through Task 2, there is really no difference to having the
SortedInventory or not at all since the local method only calls
super() then "returns". [side note: no
return is the same as
return None.] Without the
SortedInventory.add_item method, the parent's method would have been called as a matter of course.
It's Task 3 where the advantage of using
super() becomes evident. Additional code can be executed after the parent method returns back to local method execution. In fact, sometime you may want to run code before the super() [before the parent's method], or both before and after the super() [if you need some pre- and post-processing]
item is needed so it can be passed along to the parent's method since the parameter list for both the methods (a.k.a., their signatures) need to match.
Post back if you need more help. Good luck!