Although the Fib instance can be used in for loops and looks a bit like a list, it is still not possible to use it as a list. For example, take the 5th element:
>>> Fib()[5] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Fib' object does not support indexing
To behave like a list and retrieve elements by subscript, you need to implement the __getitem__() method:
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 item in the sequence by pressing the 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__
To make instances of a class use subscripts like a list, you can set the __getitem__ method. For example:
class _List(object): def __getitem__(self, key): print key l = _List() l[3] # print 3
But if you want to use slicing operation
l[1:4] # print slice(1, 4, None)
A slice object will be created for slicing. You can check the specific operation through help(slice).
a = slice(1, 4, None) range(5)[a] # print [1, 2, 3]
More abundant 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, return the list element. If it is a slice object, create an instance and return it.