Python: 用简单的代码解释yield的用法

最近看到好几篇关于关键字yield的文章,一说与stack pop相近,一说与return相近?Generator? 搞得一团糟糟的…
直接上官网查找下相关资料,搜索结果:
Python yield官方网站搜索

  1. PEP 342 – Coroutines via Enhanced Generators
  2. PEP 255 – Simple Generators
  3. PEP 380 – Syntax for Delegating to a Subgenerator
  4. PEP 525 – Asynchronous Generators
  5. PEP 340 – Anonymous Block Statements
  6. PEP 3152 – Cofunctions

    这种PEP应该是一种修改草案之类的。文字比较多看的“头疼”。从标题可以看出,关键字眼多为“coroutine" “generator” “cofunction”。说明yield关键字跟generator coroutine cofunction有关。这种比较专业详细。简单点的应该看python官方的reference手册。
    6.2.9. Yield expressions
    标题中的“expressions"表明yield语句是一个expression–表达式。

yield_atom ::= “(” yield_expression “)”
yield_expression ::= “yield” [expression_list | “from” expression]

这种类型是自然语言描述还是语法树描述?

The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator, and using it in an async def function’s body causes that coroutine function to be an asynchronous generator.

这里大概解释yield的定义–yield是一个关键字。yield语句是一个yield expression–表达式。当用来定义generator function的时,yield表达式只能在一个function函数/方法内部。最后一句:用在async def 函数/方法里会是该函数/方法变成asynchronous状态–也即异步的。
例子:

For example:
def gen(): # defines a generator function
yield 123
async def agen(): # defines an asynchronous generator function
yield 123

Yield expressions are allowed anywhere in a try construct.

Yield表达式可以用在try结构里的任意位置。原文中提到yield定义的function既是generator,就可以通过for、next()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值