# 迭代器实现给出0-n数字的平方
class Square1:
def __init__(self,count):
self.count = count
self.current = 0
def __iter__(self):
return self
def __next__(self):
result = self.current ** 2
self.current += 1
if self.current > self.count:
raise StopIteration
return result
for n in Square1(3):
print(n)
# 生成器实现0-n数字的平方
class Square2:
def __init__(self,count):
self.count = count
def square(self):
for n in range(self.count):
yield n ** 2
for n in Square2(3).square():
print(n)
python 迭代器与生成器例子
最新推荐文章于 2024-04-30 19:24:04 发布