迭代器和索引可访问的 Python 类

2022-01-10 00:00:00 python list iterator

问题描述

可能是一个 n00b 问题,但我目前有一个实现迭代器的类,所以我可以做类似的事情

Might be a n00b question, but I currently have a class that implements an iterator so I can do something like

for i in class():

但我希望能够像索引一样访问类

but I want to be able to access the class by index as well like

class()[1]

我该怎么做?

谢谢!


解决方案

同时实现 __iter__()__getitem__() 等方法.

Implement both __iter__() and __getitem__() et alia methods.

相关文章