I want to override a method of the class dict in Python, a simple one: update. Let’s say I want to create a MyDict class which is identical to standard dict except that it can be updated with dicts that have to contain at least 10 elements.
So I would proceed like:
def update(self, newdict):
if len(newdict) <= 10: raise Exception
self.update(newdict)
But in the inner call to update, obviously Python calls the overridden function and not the original one. Is there a way to avoid this situations other than simply changing the function names?
You need to call
updateon the superclass, supplying an instance of the subclass asself.You can also use
super()to determine the superclass at runtime:In Python 3, you can omit the parameters to
super():