关于yield和generator,请大神解答
#扩展阅读:解释yield和Generors#以下标了condition 1和condition 2,均可自主实现指定功能,唯一不明的是
#为什么如果不是“number=yield number”,而是“yield number”,
#send就不会起到应有的作用?
def isPrime(Num):
if Num==1:
return False
elif Num==2:
return True
else:
for i in range(2, Num//2+1):
if Num%i==0:
return False
return True
def getPrime(number):
while True:
if isPrime(number):
yield number #condition 1
## number=yield number #condition 2
number+=1
def printSuccessivePrime(iterations, base=10):
primeGenerator=getPrime(base)#condition 2
primeGenerator.send(None)#condition 2
for power in range(iterations):
## print(next(getPrime(base**power)))#condition 1
print(primeGenerator.send(base**power))#condition 2
#注,当getPrime()处于condition 1,有以下:
>>> a=getPrime(100)
>>> a.send(None)
101
>>> a.send(1000)
103
>>> a.send(10000)
107
>>> a.send(100000)
109
页:
[1]