Python 包装字典的可迭代集合

Python iterable collection that wraps a dictionary

我正在尝试修改以下代码,以便 MyCollection 包装字典。我仍然必须实现 iternext 方法才能获得 "for element in collection" 功能。我知道这可以通过遍历值轻松完成,但我需要这样做。有人可以帮助我吗?

class MyCollection:
    def __init__(self):
        self._data = []  // should be {}

    def __iter__(self):
            '''
        Return an iterator
        '''
        self._iterPoz = 0
        return self

    def __next__(self):
        '''
        Returns the next element of the iteration
        '''
        if self._iterPoz >= len(self._data):
            raise StopIteration()
        rez = self._data[self._iterPoz]
        self._iterPoz = self._iterPoz + 1
        return rez

这始于设计决策。当你迭代MyCollection时你想要什么数据?如果它是包含字典的值,你可以 return 它的迭代器然后你根本不实现 __next__

class MyCollection:
    def __init__(self):
        self._data = {}

    def __iter__(self):
            '''
        Return an iterator of contained values
        '''
        return iter(self._data.values())