Specification Summary
1. Redefine "yield" to be an expression, rather than a statement. The current yield statement would become a yield expression whose value is thrown away. A yield expression‘s value is None whenever the generator is resumed by a normal next() call.
除了作为一个statement将一个函数变成一个generator以外,yield可以被视为是一个表达式,并用于赋值。
比如
>>> def whizbang(): for i in range(10): x = yield i print ‘got sent:‘, x >>> i = whizbang() >>> next(i) 0 >>> next(i) got sent: None 1 >>> i.send("hi") got sent: hi 2
2. Add a new 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, or raises StopIteration if the generator exits without yielding another value.
见1,一个yield expression如果不通过send传入一个值,那么其值就默认是None 其余见https://www.python.org/dev/peps/pep-0342/
时间: 2024-10-19 09:38:37