为什么不使用“and”?和“或” Python 中的运算符?

发布于 2024-08-16 21:32:45 字数 217 浏览 4 评论 0原文

我不知道这一点,但显然 andor 关键字不是运算符。它们不会出现在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

悲喜皆因你 2024-08-23 21:32:45

因为它们是控制流结构。具体来说:

  • 如果 and 的左侧参数计算结果为 False,则根本不会计算右侧参数;
  • 如果 or 的左侧参数计算结果为 True,则右侧参数不会计算根本不被评估

因此,这不仅仅是保留字的问题。它们的行为不像运算符,因为运算符总是评估它们的所有参数。

您可以将其与按位二元运算符进行对比,顾名思义,按位二元运算符是运算符:

>>> 1 | (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 1 or (1/0)
1

如您所见,按位 OR (|) 计算其两个参数。然而,当左参数计算结果为 True 时,or 关键字根本不计算其右参数;这就是为什么第二个语句中没有引发 ZeroDivisionError

Because they're control flow constructs. Specifically:

  • if the left argument to and evaluates to False, the right argument doesn't get evaluated at all
  • if the left argument to or evaluates to True, the right argument doesn't get evaluated at all

Thus, 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:

>>> 1 | (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> 1 or (1/0)
1

As you see, the bitwise OR (|) evaluates both its arguments. The or keyword, however, doesn't evaluate its right argument at all when the left argument evaluates to True; that's why no ZeroDivisionError is raised in the second statement.

甜妞爱困 2024-08-23 21:32:45

Python 目前不提供任何与“and”、“or”和“not”布尔运算符相对应的“xxx”特殊方法。在“and”和“or”的情况下,最可能的原因是这些运算符具有短路语义,即如果可以从第一个操作数确定结果,则不计算第二个操作数。因此,为这些运算符提供特殊方法的常用技术将不起作用。

资料来源:PEP 335

PEP 335 讨论添加可重载运算符的能力,并稍微讨论一下这个问题。

Python does not currently provide any 'xxx' special methods corresponding to the 'and', 'or' and 'not' boolean operators. In the case of 'and' and 'or', the most likely reason is that these operators have short-circuiting semantics, i.e. the second operand is not evaluated if the result can be determined from the first operand. The usual technique of providing special methods for these operators therefore would not work.

Source: PEP 335

PEP 335 talks about adding the ability to have overloadable operators, and discusses this issue a bit.

蓝梦月影 2024-08-23 21:32:45

您正在查看的列表位于描述 Python 词汇结构的文档部分:Python 代码由哪些类型的标记组成。就词汇结构而言,所有具有标识符结构的标记都被分类为标识符关键字,无论其语义角色如何。这包括所有由字母组成的令牌。

andor 出现在 关键字标记列表而不是运算符标记列表,因为它们由字母组成:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

如果它们拼写为 &&|| andor 的情况下,它们会出现在操作符标记列表中。

在文档中未讨论词法结构的部分中,andor 被视为运算符。例如,它们列在 运算符优先级表中的运算符列下

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 and or appear in the list of keyword tokens rather than the list of operator tokens because they are composed of letters:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

If they were spelled && and || instead of and and or, they would have appeared in the list of operator tokens.

In sections of the docs that aren't talking about the lexical structure, and and or are considered operators. For example, they're listed under the Operator column in the operator precedence table.

嗫嚅 2024-08-23 21:32:45

他们在文档的前面将它们分类为关键字。

They're classifying them as keywords earlier in the document.

陪你搞怪i 2024-08-23 21:32:45

它们是关键字,因为它们是保留标识符,而不是特殊标记符号。

They're keywords, because they're reserved identifiers, not special tokens of symbols.

格子衫的從容 2024-08-23 21:32:45

它们不能被重新定义以支持特定于类型的操作,因此它们不属于其他运算符的范围。

They can't be redefined to support type-specific operations, so they don't fall under the scope of the other operators.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文