In Python, everything has a class. Therefore dict also has a class.
So, in theory, I should be able to change the implementation of the keyvalue assignment behavior.
Example:
d = dict()
d['first'] = 3 # Internally d['first'] is stored as 6 [i.e. value*2 if value is INT]
print d['first'] # should print 6
d['second'] = 4
print d['second'] # should print 8
I noticed that most objects have attributes listed in OBJECT.__dict__ or vars(OBJECT). But this isn’t the case for dict or list.
How can I get the desired behavior by overriding dict.__setattr__() method?
It is
__setitem__that have to be overriden in this case –and it is as simples as:
Example:
__setattr__controls how object attributes themselves (not key/value pairs) are attributed.