'''
定义MyRange类,实现下列功能
for item in MyRange(999999999999999999):
print(item) #0 1 2 3 4 .......999999999999999999
'''
class MyRangeIterator:
def __init__(self,stop):
self.__start = -1
self.__stop = stop
def __next__(self):
if self.__start >= self.__stop -1:
raise StopIteration
self.__start += 1
return self.__start
class MyRange:
def __init__(self,stop_value):
self.__stop_value = stop_value
def __iter(self):
return MyRangeIterator(self.__stop_value)
for item in MyRange(999999999999999999):
print(item)
#这么大的数,不会撑爆内存,因为每次__next__()返回一个数给变量item,之前的数就销毁了
python range()原理
最新推荐文章于 2023-12-29 12:17:17 发布