gpt4 book ai didi

python - 为什么 yield 函数在 Python 中不需要括号?

转载 作者:太空狗 更新时间:2023-10-29 21:14:03 25 4
gpt4 key购买 nike

在 Python 中,我多次看到用于创建生成器的 yield 函数。这个函数和 print 函数在技术上都执行方法的操作,因为它们返回一个值。然而,在从 Python 2 到 Python 3 的转换过程中,print 函数像普通方法调用一样获得了括号,但 yield 保持不变。此外,yield 获得保留关键字的淡黄色,而 print 是保留方法的紫色。为什么 yield 不被视为一种方法并以这种方式着色而不使用括号语法?

(同理,为什么return也没有括号?)

让我再补充一些东西,yield 和 continue 在许多其他语言中也没有括号。我只是想知道是什么让它与众不同,而不是保留。还有许多其他的保留方法,它们有括号。

最佳答案

所以我开始寻找答案。 And it turns out, there is one .来自 PEP 255,给我们 yield 关键字的 pep

Q. Why a new keyword for "yield"? Why not a builtin function instead?

A. Control flow is much better expressed via keyword in Python, and yield is a control construct. It's also believed that efficient implementation in Jython requires that the compiler be able to determine potential suspension points at compile-time, and a new keyword makes that easy. The CPython referrence implementation also exploits it heavily, to detect which functions are generator- functions (although a new keyword in place of "def" would solve that for CPython -- but people asking the "why a new keyword?" question don't want any new keyword).

Q: Then why not some other special syntax without a new keyword? For example, one of these instead of "yield 3":

   return 3 and continue
return and continue 3
return generating 3
continue return 3
return >> , 3
from generator return 3
return >> 3
return << 3
>> 3
<< 3
* 3

A: Did I miss one ? Out of hundreds of messages, I counted three suggesting such an alternative, and extracted the above from them. It would be nice not to need a new keyword, but nicer to make yield very clear -- I don't want to have to deduce that a yield is occurring from making sense of a previously senseless sequence of keywords or operators. Still, if this attracts enough interest, proponents should settle on a single consensus suggestion, and Guido will Pronounce on it.

关于python - 为什么 yield 函数在 Python 中不需要括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31468049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com