>>> classTest(object): ... def__init__(self): ... pass ... def__iter__(self): ... for i in range(5): ... yield i ... >>> x = Test() >>> print(isinstance(x, Iterator)) False >>> print(isinstance(x, Iterable)) True >>> print(isinstance(iter(x), Iterator)) True >>> print(isinstance(iter(x), Iterable)) True
上边资料三中也介绍到了这个部分,只有__iter__那么这个对象只是一个Iterable的对象。 但是当调用iter时即调用了对象的__iter__方法,因为这个方法内有yield,所以这个方法并不会返回,而是直接把这个方法作为了一个generator,也就变成了和代码段一一样的一个情况,使得新的对象既可Iterable又可Iterator,当然也可以使用for去遍历。资料三中提到,在调用for的时候,实际上会自动转换为for i in iter(x)。
>>> classTest(object): ... def__init__(self): ... pass ... def__iter__(self): ... return self ... def__next__(self): ... for i in range(5): ... yield i ... >>> for i in Test(): ... print(i) ... <generator object Test.__next__ at 0x7f0325db1950> <generator object Test.__next__ at 0x7f0325db1a50> <generator object Test.__next__ at 0x7f0325db1950> <generator object Test.__next__ at 0x7f0325db1a50> <generator object Test.__next__ at 0x7f0325db1950> <generator object Test.__next__ at 0x7f0325db1a50> <generator object Test.__next__ at 0x7f0325db1950> <generator object Test.__next__ at 0x7f0325db1a50> <generator object Test.__next__ at 0x7f0325db1950> <generator object Test.__next__ at 0x7f0325db1a50> <generator object Test.__next__ at 0x7f0325db1950> <generator object Test.__next__ at 0x7f0325db1a50>