为什么不使用“and”?和“或” Python 中的运算符?
我不知道这一点,但显然 and
和 or
关键字不是运算符。它们不会出现在 Python 运算符列表中。只是出于纯粹的好奇,这是为什么?如果他们不是运营商,那么他们到底是什么?
I wasn't aware of this, but apparently the and
and or
keywords aren't operators. They don't appear in the list of python operators. Just out of sheer curiosity, why is this? And if they aren't operators, what exactly are they?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为它们是控制流结构。具体来说:
and
的左侧参数计算结果为 False,则根本不会计算右侧参数;or
的左侧参数计算结果为 True,则右侧参数不会计算根本不被评估因此,这不仅仅是保留字的问题。它们的行为不像运算符,因为运算符总是评估它们的所有参数。
您可以将其与按位二元运算符进行对比,顾名思义,按位二元运算符是运算符:
如您所见,按位 OR (
|
) 计算其两个参数。然而,当左参数计算结果为 True 时,or
关键字根本不计算其右参数;这就是为什么第二个语句中没有引发ZeroDivisionError
。Because they're control flow constructs. Specifically:
and
evaluates to False, the right argument doesn't get evaluated at allor
evaluates to True, the right argument doesn't get evaluated at allThus, it is not simply a matter of being reserved words. They don't behave like operators, since operators always evaluate all of their arguments.
You can contrast this with bitwise binary operators which, as the name implies, are operators:
As you see, the bitwise OR (
|
) evaluates both its arguments. Theor
keyword, however, doesn't evaluate its right argument at all when the left argument evaluates to True; that's why noZeroDivisionError
is raised in the second statement.资料来源:PEP 335
PEP 335 讨论添加可重载运算符的能力,并稍微讨论一下这个问题。
Source: PEP 335
PEP 335 talks about adding the ability to have overloadable operators, and discusses this issue a bit.
您正在查看的列表位于描述 Python 词汇结构的文档部分:Python 代码由哪些类型的标记组成。就词汇结构而言,所有具有标识符结构的标记都被分类为标识符或关键字,无论其语义角色如何。这包括所有由字母组成的令牌。
and
和or
出现在 关键字标记列表而不是运算符标记列表,因为它们由字母组成:如果它们拼写为
&&
和||
and
和or
的情况下,它们会出现在操作符标记列表中。在文档中未讨论词法结构的部分中,
and
和or
被视为运算符。例如,它们列在 运算符优先级表中的运算符列下。The list you're looking at is in the section of the docs describing Python's lexical structure: what kinds of tokens Python code is composed of. In terms of the lexical structure, all tokens with the structure of an identifier are classified as identifiers or keywords, regardless of their semantic role. That includes all tokens made of letters.
and
andor
appear in the list of keyword tokens rather than the list of operator tokens because they are composed of letters:If they were spelled
&&
and||
instead ofand
andor
, they would have appeared in the list of operator tokens.In sections of the docs that aren't talking about the lexical structure,
and
andor
are considered operators. For example, they're listed under the Operator column in the operator precedence table.他们在文档的前面将它们分类为关键字。
They're classifying them as keywords earlier in the document.
它们是关键字,因为它们是保留标识符,而不是特殊标记符号。
They're keywords, because they're reserved identifiers, not special tokens of symbols.
它们不能被重新定义以支持特定于类型的操作,因此它们不属于其他运算符的范围。
They can't be redefined to support type-specific operations, so they don't fall under the scope of the other operators.