class Indexer:
def __getitem__(self, index): #重载索引,对于实例的索引运算,会自动调用__getitem__
return index**2
x=Indexer()
print(x[3]) #9
for i in range(5):
print(x[i], end=', ') #0, 1, 4, 9, 16,
print()
class Indexer2:
data=[1,2,3,4,5]
def __getitem__(self, index): #重载索引,对于实例的索引运算,会自动调用__getitem__
print('getitem:', index)
return self.data[index]
def __setitem__(self, index, value): #重载索引赋值,对于实例的索引赋值,会自动调用__setitem__
print('setitem:')
self.data[index]=value
def __index__(self):
return 255
x=Indexer2()
print(x[0]) #getitem: 0 1
print(x[:-1]) #getitem: slice(None, -1, None) [1, 2, 3, 4]
print(x[1::]) #getitem: slice(1, None, None) [2, 3, 4, 5]
print(x[2:4]) #getitem: slice(2, 4, None) [3, 4]
print(bin(x), bin(255)) #0b11111111 0b11111111
print(('a'*256)[x]) #a
#索引迭代:__getitem__
class stepper:
def __getitem__(self, index):
return self.data[index]
x=stepper()
x.data='spam'
for i in x:
print(i, end=', ') #s, p, a, m,
#所有支持迭代的类也会自动支持python所有迭代环境
print('s' in x) #True
print([i for i in x]) #['s', 'p', 'a', 'm']
print(list(map(str.upper, x))) #['S', 'P', 'A', 'M']
(a,b,c,d)=x
print(a,b,c,d) #s p a m
print(list(x), tuple(x),''.join(x)) #['s', 'p', 'a', 'm'] ('s', 'p', 'a', 'm') spam