且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

此类如何实现"__iter__"没有实现“下一个"的方法?

更新时间:2021-08-13 06:28:47

来自 docs :

如果容器对象的__iter__() 方法被实现为生成器, 它将自动返回一个 迭代器对象(从技术上讲, 生成器对象)提供 __iter__()__next__()方法.

If a container object’s __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and __next__() methods.

以下是您使用生成器提供的示例:

Here is your provided example using a generator:

class A():
    def __init__(self, x=10):
        self.x = x
    def __iter__(self):
        for i in reversed(range(self.x)):
            yield i

a = A()
for item in a:
    print(item)