Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMichael Cook
Full Stack JavaScript Techdegree Graduate 28,975 PointsI'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):
self.slots.append(item)
class SortedInventory(Inventory):
pass
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsGreat 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!!