A dict
object does not store keys and values in a __dict__
attribute; how could it, as the __dict__
attribute is itself a dict
object!
Use the overridden __setitem__
method to add to the dictionary; best practice is to use super()
to look up the original method:
class MyDict(dict):
def __setitem__(self, k, v):
print 'assignment', k, v
super(MyDict, self).__setitem__(k, v)
You could also use the unbound dict.__setitem__
method:
class MyDict(dict):
def __setitem__(self, k, v):
print 'assignment', k, v
dict.__setitem__(self, k, v)
except that would hardcode the method and not len subclasses of your custom myDict
class inject another intermediary __setitem__
method.