使用 send in python 这两个函数有什么不同

What's different from these two functions using send in python

我正在 python 学习生成器,这里有函数:

import math
def is_primes(number):
    if number > 1:
        if number == 2:
            return True
        if number % 2 == 0:
            return False
        for current in range(3, int(math.sqrt(number) + 1), 2):
            if number % current == 0:
                return False
        return True
    return False


def get_primes1(number):
    while True:
        if is_primes(number):
            yield number
        number +=1

def get_primes2(number):
    while True:
        if is_primes(number):
            number=yield number
        number +=1

使用发送功能时:

a=get_primes1(2)
b=get_primes2(2)
a.send(None)#return 2
b.send(None)#return 2
a.send(1)#return 3,the parameter in send() looks useless.
b.send(1)#return 1,normal

当重复使用 "a.send(1)" 和 "b.send(1)" 时,a.send(1) return 较大的值,但 b.send(1) 仍然 return一样value.why有区别吗?

我检查发送函数的含义:

Resumes the execution and ``sends'' a value into the generator function. The value argument becomes the result of the current yieldexpression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receieve the value.

how the send function work in generator?

def counter():
    total = 0

    while True:
        increment = yield total  #If next() was called, 
                                 #increment is assigned None. 
                                 #If send() was called,
                                 #increment is assigned send()'s argument.

        if increment:
            total += increment
        else:
            total += 1


g = counter()
print(next(g))
print(next(g))
print(g.send(3))
print(next(g))

--output:--
0
1
4
5

A yield expression's value is None whenever the generator is resumed by a normal next() call.


send() method for generator-iterators, which resumes the generator and "sends" a value that becomes the result of the current yield-expression. The send() method returns the next value yielded by the generator

PEP 342

but b.send(1) still return the same value.why there is difference?

因为你一遍又一遍地将 number 重置为 send() 参数的值:

a:  number = 2
    number += 1
    number += 1

b:  number = 2
    number = 1
    number += 1
    number = 1
    number += 1