【问题标题】:How to delegate `__iter__` method in Python如何在 Python 中委托 __iter__ 方法
【发布时间】:2021-03-01 05:43:50
【问题描述】:

我想将__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

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

【问题讨论】:

标签: python python-3.x metaprogramming


【解决方案1】:

为什么要把事情复杂化?

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

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

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 2016-11-10
    • 2016-08-21
    相关资源
    最近更新 更多