Python 中可迭代类的最小示例
这是一个类似生成器的可迭代自定义类的最小示例:
iterable_example.py
class MyIterable(object):
def __init__(self):
pass # ... 你的代码放在这里!
def __iter__(self):
# 通常不需要修改这个!
return self
def __next__(self):
# 要表示没有更多值,使用:raise StopIteration
return "test" # 在这里返回下一个值。返回 n用法示例:
iterable_usage.py
it = MyIterable()
print(next(it)) # 打印 "test"
print(next(it)) # 打印 "test"如果你想阅读更多关于如何创建自己的迭代器的内容,我推荐此教程。
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow