class Range:
def __init__(self, start, stop=None, step=1):
if stop is None:
self.start = 0
self.stop = start
else:
self.start = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
# 每次循环返回当前的值.
if self.start < self.stop:
# 更新self.start
res = self.start
self.start = self.start + self.step
return res
else:
raise StopIteration()
使用迭代器,实现原生的range功能.
最新推荐文章于 2024-07-17 17:38:43 发布