[Python] How to mimic Python's dict.items() functionality in a custom class [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 23, 2025.

  1. Stack

    Stack Membro Participativo

    In Python, I am creating a quasi-dictionary like thing (custom class that looks or acts like a dictionary in many ways, but is not a dict subclass).

    I would like to support the standard foo.items() found in a dictionary

    But what I do not know is the self.__magic__() method name that I need to implement for my custom class.

    I know for example, __setattr__(), __getattr__(), and I see that a dict has a __getitem__() method, but the docs say it requires a key - what key is going to be used here? I would have expected an index, or yield like method that returns the name/value tuple but I do not see that.

    An example of doing this would also be helpful. Google only seems to find how to extend the dict, and that is not what I am doing.

    Do I just implement my own class.items() function as a generator?

    Continue reading...

Compartilhe esta Página