Website Explanation:
object.
__getitem__
(Self, key)
Called to implement evaluation ofself[key]
.for sequence types,The accepted keys should beintegers andSlice Objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) are up to the__getitem__()
Method. IfKeyis of a inappropriate type,TypeError
May is 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, ifKeyIs missing (not in the container),KeyError
should be raised.
Note:
for
Loops expect that anIndexError
Would be raised for illegal indexes to allow proper detection of the end of the sequence.
For the Fibonacci sequence, when we want to extract the value of a particular position to see, then what to do, and then come out __getitem__ such a function.
int, List type: Slice (no step)
#!/usr/bin/python
#-*-Coding:utf-8-*-
Class Fib (object):
def __getitem__ (self, N):
If Isinstance (n, int): # N is an index
A, B = 1, 1
For x in range (n):
A, B = B, A + b
Return a
If Isinstance (n, Slice): # N is a slice
Start = N.start
Stop = N.stop
If Start is None:
Start = 0
A, B = 1, 1
L = []
For x in range (stop):
If x >= start:
L.append (a)
A, B = B, A + b
Return L
f = Fib ()
Print F[0:4]
Print F[9]
Python Class: Object-oriented advanced programming __getitem__