1.__getitem__()
#!/usr/bin/python3.8.12
# -*- coding: utf-8 -*-
# @Time : 2022/4/16 上午10:21
# @Author : pf
# @Software: PyCharm
class MutiplyByTwo:
def __init__(self,number):
self.numbers=numbers
self.counter=0
def __getitem__(self,index):
input_dict = {
'number':self.numbers[index],
'counter':self.counter}
return input_dict
if __name__=="__main__":
numbers=[1,2,3]
MutiplyByTwo=MutiplyByTwo(numbers)
for num in MutiplyByTwo:
print(num)
输出结果
说明:__getitem__方法在类的实例被迭代的时候会被调用,也就是说,在for循环中,会先判断MutiplyByTwo是不是一个可迭代对象,比如list,dict,trule,set,这些都是可迭代对象。然后会根据迭代索引index返回数据,注意没有index系统会报错,index相当于一个计数器。
2. __next__()
#!/usr/bin/python3.8.12
# -*- coding: utf-8 -*-
# @Time : 2022/4/16 上午10:21
# @Author : pf
# @Software: PyCharm
class MutiplyByTwo:
def __init__(self,numbers):
self.numbers=numbers
self.counter=0
def __iter__(self):
print("__iter__")
return self
def __next__(self):
self.counter +=1
if self.counter >= self.numbers:
raise StopIteration()
return self.counter
if __name__=="__main__":
numbers=10
MutiplyByTwo=MutiplyByTwo(numbers)
for i in MutiplyByTwo:
print(i)
结果
?
?每次for循环的时候都会调用__next__(),而__iter__()只是在for第一次被调用,并且__iter__必须返回self,否则next()不起作用,可以看出__getitem__(self,index)是__next__(self)和__iter__(self)的组合。
|