启用Python类以支持通过内部可迭代成员变量进行循环

q0987
from sortedcontainers import SortedSet

class BigSet(object):
    def __init__(self):
        self.set = SortedSet()
        self.current_idx = -1

    def __getitem__(self, index):
        try:
            return self.set[index]
        except IndexError as e:
            print('Exception: Index={0} len={1}'.format(index, len(self.ord_set)))
            raise StopIteration

    def add(self, element):
        self.set.add(element)

    def __len__(self):
        return len(self.set)

    def __iter__(self):
        self.current_idx = -1
        return self

    def __next__(self):
        self.current_idx += 1
        if self.current_idx == len(self.set):
            raise StopIteration
        else:
            return self.set[self.current_idx]

def main():
    big = BigSet()
    big.add(1)
    big.add(2)
    big.add(3)

    for b in big:
        print(b)

    for b2 in big:
        print(b2)

if __name__ == "__main__":
    main()

我有一个嵌入名为的可迭代成员变量的类,self.set并且我想启用此类以支持for循环。上面是我为此目的编写的代码。但是,我认为必须有更好的方法来简化此任务,因为该类已经有一个可迭代的成员。

问题>有什么方法可以将作业委派给嵌入式self.set另外,我认为也许也有实现它的好方法__getitem__

谢谢

胡安帕·阿里维利亚加

几乎可以肯定,您不希望您的容器成为迭代器因此,它不应该实现 __next__相反,它应该是可迭代的,因此只需实现即可__iter__在这种情况下,如果要委派给可迭代成员:

def __iter__(self):
    return iter(self.set)

并删除您的__next__方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章