gpt4 book ai didi

python - 如何在字典初始化时调用 __set_item__?

转载 作者:行者123 更新时间:2023-12-05 04:54:46 28 4
gpt4 key购买 nike

下面是继承自dict的类MyDict。我想要什么do 基本上是每次 a 的一个键执行一些操作MyDict 对象被赋值。所以 __setitem__ 是我的 friend 这里:

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!"

这很棒,但现在如果我这样做,__setitem__ 将不再被调用。

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

我当然可以重载 __init__ 来解决我的问题,但是有更简单的解决方案吗?

此外,据我了解 dict.__init__ 帮助信息:

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

__setitem__ 应该在我的示例中调用。我是不是误会了什么?

最佳答案

你应该继承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!'})

输出

key 0 set to hello
key 1 set to world!

相关问题:Subclass dict: UserDict, dict or ABC?list vs UserList and dict vs UserDict

关于python - 如何在字典初始化时调用 __set_item__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65645705/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com