gpt4 book ai didi

python - 如何在Python中委托(delegate) `__iter__`方法

转载 作者:行者123 更新时间:2023-12-02 02:21:06 24 4
gpt4 key购买 nike

我想为可迭代容器委托(delegate) __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)

输出为

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

请告诉我如何委托(delegate) __iter__ 方法。

最佳答案

为什么让事情变得过于复杂?

class DelegateIterator:
def __init__(self, container):
self.container = container

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

关于python - 如何在Python中委托(delegate) `__iter__`方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66417196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com