繁体   English   中英

如何在 Python 中委托 __iter__ 方法

[英]How to delegate `__iter__` method in Python

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

output 是

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

请让我知道如何委托__iter__方法。

为什么要把事情复杂化?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM