Describes the _ getitem _ method in Python and slice object slicing operations,
Although the Fib instance can act on a for loop, it looks a little like a list, but it still cannot be used as a list, for example, taking 5th elements:
>>> Fib()[5]Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'Fib' object does not support indexing
To retrieve elements by subscript like list, the _ getitem _ () method must be implemented:
class Fib(object): def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a
Now, you can access any of the series by Subscript:
>>> f = Fib()>>> f[0]1>>> f[1]1>>> f[2]2>>> f[3]3>>> f[10]89>>> f[100]573147844013817084101
Slice object and _ getitem __
You can set the _ getitem _ method to make the instance of the class use the subscript like the list. For example:
class _List(object): def __getitem__(self, key): print keyl = _List()l[3] # print 3
However, if you want to use the slice operation
l[1:4] # print slice(1, 4, None)
A slice object is created for slicing. You can view the specific operation through help (slice.
a = slice(1, 4, None)range(5)[a] # print [1, 2, 3]
Richer operations
class _List(object): def __init__(self, _list): self._list = _list def __getitem__(self, key): if isinstance(key, int): return self._list[key] elif isinstance(key, slice): reutrn self.__class__(self._list[key])if __name__ == '__main__': c = _List(range(10)) b = c[1:5] print b[3] # print 4
If the key is an integer, the list element is returned. If the key is an slice object, an instance is created and a result is returned.