Python的__getitem__(self,n)方法为拦截索引运算
当实例s出现s[i]这样的索引运算时,Python会调用这个实例s继承的__getitem__(self,n)方法,并把s作为第一个参数传递(self),将方括号内的索引值 i 传递给第二个参数 n
>>>class Square():
def __getitem__(self,n):
return n**2
>>>s = Square()
>>>s[2]
4
>>>s[6]
36
>>>class Fib():
def __getitem__(self,n):
a,b = 1,1
for x in range(n):
a,b = b, a + b
return a
>>> f = Fib() #创建了一个实例f
>>>f[0] # n = 0, x in range(0)--- x 为空, a = 1
1
>>>f[1] # n = 1, x = 0, a = b = 1,b=2
1
>>>f[2] # n = 2, x=1,a=b=2,b=3
2
>>>class Fib():
def __init__(self):
self.a,self.b = 0, 1
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 10000:
raise StopIteration()
return self.a
def __getitem__(self,n):
a,b = 1,1
for x in range(n):
a,b = b, a + b
return a
>>> f = Fib() #现在实例 f 既可以迭代,又可以根据索引来取值
>>>for i in f: #此时Python先寻找__iter__()方法,返回迭代器对象f(实例),它继承了Fib()类的__next__()方法,接下来Python会重复调用实例 f 的next方法,直到抛出StopIteration异常
print(i)
.......
>>>f[0]
1
>>>f[5]
8