我正在尝试编写一个继承自字典并覆盖__setitem__
和__getitem__
的类,一切都很顺利,直到我注意到items
和values
为止不要使用__getitem__
。有人知道如何覆盖他们的查找功能吗?
以下示例实现:
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
答案 0 :(得分:2)
根据有关模拟容器类型(https://docs.python.org/3.5/reference/datamodel.html#emulating-container-types)的文档,您应该直接实现items()
和values()
(以及其他一些)。
实施__iter__
可能会有所帮助,因为这就是很多这些功能所做的事情,但你应该在这里查看文档。
答案 1 :(得分:1)
您可以覆盖 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)
据我所知,字典不是在Python本身实现。因此,他们不使用Python代码来获取密钥或值。因为__getitem__
在解释器级别实现,所以简单地覆盖values()
将不起作用。 This is for instance the source code of a Python dictionary of Python 2.6.6