作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面是继承自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/
下面是继承自dict的类MyDict。我想要什么do 基本上是每次 a 的一个键执行一些操作MyDict 对象被赋值。所以 __setitem__ 是我的 friend 这里: class MyDic
我是一名优秀的程序员,十分优秀!