实际案例:
- 实现一个可迭代对象的类,它能迭代出给定范围内所有素数:
pn = PrimeNumbers(1,30)
for k in pn:
print(k)
输出结果:2,3,5,7,11,13...
首先熟悉生成函数的特点:
def f():
print('in f() ,1')
yield 1
print('in f() ,2')
yield 2
print('in f() ,3')
yield 3
生成器函数实现了迭代器的next方法
测试用例1:
g = f()
g.__next__()
g.__next__()
g.__next__()
g.__next__()
输出结果1:
in f() ,1
in f() ,2
in f() ,3
Traceback (most recent call last):
File "testBuilderDef.py", line 13, in <module>
g.__next__()
StopIteration
测试用例2:
for i in g:
print(i)
输出结果2:
in f() ,1
1
in f() ,2
2
in f() ,3
3
解决方案:
- 将该类的iter方法实现成生成器函数,每次yield返回一个素数.
class PrimeNumbers:
def __init__(self,start,end):
self.start = start
self.end = end
def isPrimeNum(self,k):
if k < 2:
return False
for i in range(2,k):
if k%i == 0:
return False
return True
def __iter__(self):
for k in range(self.start,self.end+1):
if self.isPrimeNum(k):
yield k
for x in PrimeNumbers(1,100):
print(x)
网友评论