Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

python - 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:

class MyDict(dict):
    def __setitem__(self, key, value):
        print(f'key {key} set to {value}')
        super().__setitem__(key, value)

m = MyDict()
m[0] = 'hello'   # prints "0 set to hello"
m[1] = 'world!'  # prints "1 set to world!"

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

m = MyDict({0: 'hello', 1: 'world!'})

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:

 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v

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

question from:https://stackoverflow.com/questions/65645705/how-to-call-set-item-at-dictionary-initialisation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should subclass UserDict:

from collections import UserDict

class MyDict(UserDict):
    def __setitem__(self, key, value):
        print(f'key {key} set to {value}')

m = MyDict({0: 'hello', 1: 'world!'})

Outputs

key 0 set to hello
key 1 set to world!

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...