更新时间: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)