Python Object-Oriented Python Inheritance Super!

Michael Cook
.a{fill-rule:evenodd;}techdegree seal-36
Michael Cook
Full Stack JavaScript Techdegree Graduate 28,938 Points

I'm very confused about what it means to override a method

In what sense does super() 'override' a method? The further I go through the Python track the more confused I get, and I am coming to this with a fairly strong background in another programming language. I get the concept that if we want to add unique attributes to a subclass that are initialized with init() then that would override the parent class's initializer method, so therefore super() is a way to have both unique initialized attributes AND still inherit the attributes of the parent class. But I have no idea what it means to override a method in the parent class and I'm starting to get really frustrated by the lack of clarity in the lessons and code exercises.
class Inventory:
    def __init__(self):
        self.slots = []
    def add_item(self, item):

class SortedInventory(Inventory):

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 59,730 Points

Great question! When a class method is called, the executable for the call is first searched for in the local class definition, then in each of the parent class definitions, working down the MRO (module resolution order).

When a class extends another class, it gets use of all of the parent class methods as if they were local to the extending class. The class SortedInventory automatically gets use of add_item from the parent Inventory. When SortedInventory.add_item() is called, it is looked for locally, before resolving to Inventory.add_item().

However, if a method of the same name as a parent method exists in the local definition, it is chosen instead of looking for it in one of the parents. Since this local version blocks the parents version, it is said to "override" the selection of the parents method.

So to override Inventory.add_item(), simply create a method called add_item() in SortedInventory.

Post back if you have more questions. Good Luck!!