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:
1 2 3 4 |
|
To behave like a list and retrieve elements by subscript, you need to implement the __getitem__() method:
1 2 3 4 5 6 |
|
Now, you can access any item in the sequence by pressing the subscript:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
slice object and __getitem__
To make instances of a class use subscripts like a list, you can set the __getitem__ method. For example:
1 2 3 4 5 6 7 |
|
But if you want to use slicing operation
1 |
|
A slice object will be created for slicing. You can check the specific operation through help(slice).
1 2 3 |
|
More abundant operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
If the key is an integer, return the list element. If it is a slice object, create an instance and return it.