可迭代对象
就是实现了 __iter__或者 __getitem__中的任意一个,
可以通过下标索引的,
可以通过 for 循环遍历的
如何判断呢
方法有两个,一个是
这个用的少
from collections import Iterable
print(isinstance([],Iterable))
class test:
pass
print(isinstance(test(),Iterable))
这个用的多一点
上面说了,实现了__iter__或者 __getitem__就是 可迭代的
print(hasattr([],'__getitem__'))
class test:
pass
print(hasattr(test(),'__getitem__'))
如何自己创建可迭代对象呢
class test:
def __init__(self,one):
self.one = one
a = test([1,2,3,4])
for i in a:
print(i)
这样是不可以的,因为没实现 getitem 方法
class test:
def __init__(self,one):
self.one = one
# item是一个解释器,帮我么维护的索引值,当在 for 循环中时,自动从 0 开始计数
def __getitem__(self, item):
return self.one[item]
a = test([1,2,3,4])
for i in a:
print(i)