简体   繁体   English

什么内部函数决定价值和项目使用,我如何覆盖它们?

[英]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__ ,一切都进行得很顺利,直到我注意到itemsvalues不使用__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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM