我写了一个自定义容器对象.
根据这个页面,我需要在我的对象上实现这个方法:
__iter__(self)
Run Code Online (Sandbox Code Playgroud)
但是,在跟踪Python参考手册中的Iterator类型链接后,没有给出如何实现自己的示例.
有人可以发布片段(或链接到资源),显示如何执行此操作?
我正在写的容器是一个映射(即通过唯一键存储值).dicts可以像这样迭代:
for k, v in mydict.items()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我需要能够在迭代器中返回两个元素(一个元组?).目前尚不清楚如何实现这样的迭代器(尽管已经提供了几个答案).有人可以更多地了解如何为类似地图的容器对象实现迭代器吗?(即一个像dict一样的自定义类)?
我想委托__iter__可迭代容器的方法。
class DelegateIterator:
def __init__(self, container):
attribute = "__iter__"
method = getattr(container, attribute)
setattr(self, attribute, method)
d = DelegateIterator([1,2,3])
for i in d.__iter__(): # this is successful
print(i)
for i in d: # raise error
print(i)
Run Code Online (Sandbox Code Playgroud)
输出是
1
2
3
Traceback (most recent call last):
File "test.py", line 10, in <module>
for i in d:
TypeError: 'DelegateIterator' object is not iterable
Run Code Online (Sandbox Code Playgroud)
请让我知道如何委托__iter__方法。