In [ ]:
class Number:
def __init__(self, start):
self.data = start
def __sub__(self, other):
return Number(self.data - other)
In [ ]:
X = Number(5)
Y = X - 3
Y.data
In [ ]:
class Indexer:
def __getitem__(self, index):
return index ** 2
In [ ]:
X = Indexer()
X[2]
In [ ]:
for i in range(5):
print(X[i], end=' ')
In [ ]:
L = [5, 6, 7, 8, 9]
In [ ]:
L[2:4]
In [ ]:
L[1:]
In [ ]:
L[:-1]
In [ ]:
L[::2]
In [ ]:
L[slice(2, 4)]
In [ ]:
L[slice(1, None)]
In [ ]:
L[slice(None, -1)]
In [ ]:
L[slice(None, None, 2)]
In [ ]:
class Indexer:
data = [5, 6, 7, 8, 9]
def __getitem__(self, index):
print('getitem: ', index)
return self.data[index]
In [ ]:
X = Indexer()
In [ ]:
X[0]
In [ ]:
X[1]
In [ ]:
X[-1]
In [ ]:
X[2:4]
In [ ]:
X[1:]
In [ ]:
X[:-1]
In [ ]:
X[::2]
In [ ]:
class Indexer:
def __getitem__(self, index):
if isinstance(index, int):
print('indexing', index)
else:
print('slicing', index.start, index.stop, index.step)
In [ ]:
X = Indexer()
X[99]
In [ ]:
X[1:99:2]
In [ ]:
X[1:]
In [ ]:
class StepperIndex:
def __getitem__(self, i):
return self.data[i]
In [ ]:
X = StepperIndex()
X.data = 'Spam'
X[1]
In [ ]:
for item in X:
print(item, end=' ')
In [ ]:
'p' in X
In [ ]:
[c for c in X]
In [ ]:
list(map(str.upper, X))
In [ ]:
(a, b, c, d) = X
a, c, d
In [ ]:
list(X), tuple(X), ' '.join(X)
In [ ]:
X
In [ ]: