[英]What internal function does dict value and items use, and how do I overwrite them?
I'm trying to write a class that inherits from dictionary and overwrote __setitem__
and __getitem__
and everything was going so well until I noticed that items
and values
do not use __getitem__
. 我正在尝试编写一个继承自字典并覆盖
__setitem__
和__getitem__
,一切都进行得很顺利,直到我注意到items
和values
不使用__getitem__
。 Anyone know how to overwrite their look up functions? 有谁知道如何覆盖他们的查找功能?
Example implementation below: 示例实现如下:
class ReturnStringsDict(dict):
def __getitem__(self, key):
"""Return value only."""
return str(super().__getitem__(key))
test = ReturnStringsDict()
test['a'] = 1
test['b'] = 2
# Throws assertion error.
for value in test.values():
assert isinstance(value, str)
# Throws assertion error.
for key, value in test.items():
assert test[key] == value
According to the documentation on emulating container types ( https://docs.python.org/3.5/reference/datamodel.html#emulating-container-types ), you should implement items()
and values()
(and a few others) directly. 根据有关模拟容器类型的文档( https://docs.python.org/3.5/reference/datamodel.html#emulating-container-types ),您应该实现
items()
和values()
(以及其他一些)直。
It might help to implement __iter__
, because that's what a lot of those functions do, but you should really check the docs here. 它可能有助于实现
__iter__
,因为这就是很多这些函数所做的事情,但你应该在这里检查文档。
Well you can overwrite the values()
and items()
functions: 那么你可以覆盖
values()
和items()
函数:
class ReturnStringsDict(dict):
# ...
def values(self):
for v in super().values():
yield str(v)
def items(self):
for k,v in super().items():
yield k,str(v)
As far as I know dictionaries are not implemented in Python itself. 据我所知,字典不是用Python本身实现的。 So they do not use Python code to obtain a key or value.
因此,他们不使用Python代码来获取密钥或值。 Simply overwriting the
__getitem__
will thus not work since values()
are implemented at the interpreter level. 因此,只需覆盖
__getitem__
就行不通,因为values()
是在解释器级别实现的。 This is for instance the source code of a Python dictionary of Python 2.6.6 . 这是Python 2.6.6的Python字典的源代码 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.