EDIT: According to this answer, it's a good idea to call super()
, because otherwise behavior might be undefined. I suppose my question in that case really is, how is it that my code works even without calling it? That would seem like a light switch working without anyone hooking up the electricity. So I'm more interested in the mechanics of what's going on, and not a simple "yes add it" or "no it's not necessary".
I'm working with the following python code to implement an LRU cache. It subclasses OrderedDict
in order to support the methods for the cache, namely get
and put
. It works perfectly, but I'm confused-- why don't I need to call the parent's constructor?
According to this answer, I should have to call super().__init__()
, but I don't (try for yourself).
My question is, by what mechanism does my subclass know how to insert values into itself, if nothing was initialized?
from collections import OrderedDict
class LRUCache(OrderedDict):
def __init__(self, capacity):
self.capacity = capacity
def get(self, key):
if key not in self:
return -1
self.move_to_end(key)
return self[key]
def put(self, key, value):
if key in self:
self.move_to_end(key)
elif len(self) == self.capacity:
self.popitem(last=False)
self[key] = value