官方文档释义:Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.
classMyList(): def__init__(self, anylist): self.data = anylist def__len__(self): return len(self.data) def
__getitem__(self, index): print("key is : " + str(index)) cls = type(self) if isinstance(index, slice): print("data is : " + str(self.data[index])) return cls(self.data[index]) elif isinstance(index, numbers.Integral): return self.data[index] else: msg = "{cls.__name__} indices must be integers" raise TypeError(msg.format(cls=cls))
l = MyList(["My", "name", "is", "Python猫"])
### 输出结果: key is : 3 Python猫 key is : slice(None, 2, None) data is : ['My', 'name'] <__main__.mylist style="font-size: inherit;line-height: inherit;color: rgb(209, 154, 102);overflow-wrap: inherit !important;word-break: inherit !important;">0x0000019CD83A7A90> key is : hi Traceback (most recent call last): ... TypeError: MyList indices must be integers or slices
# ob1它遍历 for i in ob1: print(i, end = " ") # a b c for i in ob1:
print(i, end = " ") # a b c # ob1自遍历 ob1.__next__() # 报错: 'str' object has no attribute '__next__'
# ob2它遍历 for i in ob2: print(i, end = " ") # a b c for i in ob2: print(i, end = " ") # 无输出 # ob2自遍历 ob2.__next__() # 报错:StopIteration
# ob3自遍历 ob3.__next__() # a ob3.__next__() # b ob3.__next__() # c ob3.__next__() # 报错:StopIteration
# 例1:简易迭代器 s = iter("123456789") for x in itertools.islice(s, 2, 6): print(x, end = " ") # 输出:3 4 5 6 for x in itertools.islice(s, 2, 6): print(x, end = " ") # 输出:9
defislice(iterable, *args): # islice('ABCDEFG', 2) --> A B # islice('ABCDEFG', 2, 4) --> C D # islice('ABCDEFG', 2, None) --> C D E F G # islice('ABCDEFG', 0, None, 2) --> A C E G s = slice(*args) # 索引区间是[0,sys.maxsize],默认步长是1 start, stop, step = s.start or0, s.stop or sys.maxsize, s.step or1 it = iter(range(start, stop, step)) try: nexti = next(it) except StopIteration: # Consume *iterable* up to the *start* position. for i, element in zip(range(start), iterable): pass return try: for i, element in enumerate(iterable): if i == nexti: yield element nexti = next(it) except StopIteration: # Consume to *stop*. for i, element in zip(range(i + 1, stop), iterable): pass
# test.txt 文件内容 ''' 猫 Python猫 python is a cat. this is the end. '''
from itertools import islice with open('test.txt','r',encoding='utf-8') as f: print(hasattr(f, "__next__")) # 判断是否迭代器 content = islice(f, 2, 4) for line in content: print(line.strip()) ### 输出结果: True python is a cat. this is the end.