Skip to content
Advertisement

How to call __set_item__ at dictionary initialisation?

Below is a class MyDict that inherits from dict. What I want to do is basically to perform some operation each time a key of a MyDict object is assigned a value. So __setitem__ is my friend here:

JavaScript

This is great but now if I do this, __setitem__ is not called anymore.

JavaScript

I could of course overload __init__ to solve my problem but is there a simpler solution?

Besides, as I understand the dict.__init__ help message:

JavaScript

__setitem__ should be called in my example. Have I misunderstood something?

Advertisement

Answer

You should subclass UserDict:

JavaScript

Outputs

JavaScript

Related questions: Subclass dict: UserDict, dict or ABC? and list vs UserList and dict vs UserDict

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement