Hi all!
I want to make a subclass of dict and I have read about subclassing and the super method.
The problem that I do not get is how I override the following method:

dict[key] = value

This creates a new key with the specified value.
I want to override this to make some file writing and the call super, how do I do this?


Many thanks in advance!
Marcux

Recommended Answers

All 6 Replies

You must overwrite the __setitem__ method

class mydict(dict):
    def __setitem__(self, key, value):
        doStuff()
        return dict.__setitem__(self, key, value)

Thanks Gribouillis!
That was exactly what I was looking for.
By the way...isn't:

dict.__setitem__(self, key, value)

The old style to call super class?
Aren't you supposed to use super, as in:

super(mydict, self).__setitem__(self, key, value)

Or have I got it all wrong with super classes?

Marcux

Well, super has been around for some time now, but it's not very useful. Better call the parent class directly.

Thanks again!
The last question regarding dict.
How do I override when a user deletes an item with:

del d[key]

Second of all where can I find this info?
It is not specified in the sandard lib. doc.

Many thanks again!
Marcux

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.