Python的魔法方法__getitem__
可以让对象实现迭代功能,这样就可以使用for...in...
,[]来迭代该对象了
class Com(object):
def __init__(self,el):
self.el = el
c = Com(['11','9','54','43'])
for i in c:
print(i)
在用 for..in..
迭代对象时,如果对象没有实现 __iter__
__next__
迭代器协议,Python的解释器就会去寻找__getitem__
来迭代对象,如果连__getitem__
都没有定义,这解释器就会报对象不是迭代器的错误:
for i in c:
TypeError: 'Com' object is not iterable
class Com(object):
def __init__(self, el):
self.el = el
def __getitem__(self, item):
return self.el[item]
c = Com(['11', '9', '54', '43'])
for i in c:
print(i)
c1 = c[:2]
print(c1)
print(type(c1))
11
9
54
43
['11', '9']
<class 'list'>