Python - Index Iteration: __getitem__

Description

Index Iteration: __getitem__

Demo

class StepperIndex: 
    def __getitem__(self, i): 
        return self.data[i] 

X = StepperIndex()                # X is a StepperIndex object 
X.data = "Test" 
print( X[1] )                     # Indexing calls __getitem__ 
for item in X:                    # for loops call __getitem__ 
   print(item, end=' ')          # for indexes items 0..N 
# from w w  w.j a  v a  2s.c o m
'p' in X                          # All call __getitem__ too 
[c for c in X]                    # List comprehension 
list(map(str.upper, X))           # map calls (use list() in 3.X) 
(a, b, c, d) = X                  # Sequence assignments 
print( a, c, d )
list(X), tuple(X), ''.join(X)     # And so on... 
print( X )

Result