Python 中的 & 符号和竖线字符在哪里?
在描述短路评估的维基百科页面中,&
和 |
在 Python 中被列为 eager 运算符。这是什么意思以及它们何时在该语言中使用?
In the Wikipedia page describing short-circuit evaluation, &
and |
are listed as eager operators in Python. What does this mean and when are they used in the language?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
维基百科页面有误,我已更正。
|
和&
不是布尔运算符,尽管它们是急切运算符,这仅意味着它们不是短路运算符。您可能知道,Pythonand
和or
运算符的工作原理如下:据我所知,Python 没有急切的布尔运算符,它们必须显式编码,例如这样:
现在,即使
or
仍然短路,调用函数时也会自动计算a
和b
。至于
|
和&
的用法,当与数字一起使用时,它们是二元运算符:你最有可能使用
|
这个使用Python绑定到使用标志的库的方式,例如wxWidgets:当与集合一起使用时,它们分别执行交集和并操作:
The wikipedia page is wrong, I've corrected it.
|
and&
are not boolean operators, even though they are eager operators, which just means that they are not short circuit operators. As you probably know, here's how the pythonand
andor
operators work:As far as I know, python has no eager boolean operators, they would have to be explicitly coded, for instance like this:
Now
a
andb
are automatically evaluated when the function is called, even thoughor
still short circuits.As for the usage of
|
and&
, when used with numbers, they are binary operators:You're most likely to use
|
this way with python bindings to libraries that uses flags, like wxWidgets:When used with sets, they do the intersection and union operations, respectively:
这里的其他答案缺少的是
&
和|
在 Python 中没有任何通用含义;它们的含义取决于操作数的类型,使用神奇的__and__
和__or__
方法。由于这些是方法,因此操作数在作为参数传递之前都会被评估(即没有短路)。在
bool
值上,它们是逻辑“与”和逻辑“或”:在
int
值上,它们是按位“与”和按位“或”:在集合上,它们是交集和 union:
一些额外的注意事项:
__and__
和__or__
方法始终在类上查找,而不是在实例上查找。因此,如果您分配 obj.__and__ = lambda x, y: ... 那么它仍然会被调用。有关更多详细信息,请参阅 Python 语言参考。
Something missing from the other answers here is that
&
and|
don't have any universal meaning in Python; their meaning depends on the operands' types, using the magic__and__
and__or__
methods. Since these are methods, the operands are both evaluated (i.e. without short-circuiting) before being passed as arguments.On
bool
values they are logical "and" and logical "or":On
int
values they are bitwise "and" and bitwise "or":On sets, they are intersection and union:
A couple of extra notes:
__and__
and__or__
methods are always looked up on the class, not on the instance. So if you assignobj.__and__ = lambda x, y: ...
then it's stillobj.__class__.__and__
that's invoked.__rand__
and__ror__
methods on the class will take priority, if they are defined.See the Python language reference for more details.
这意味着始终评估左操作数和右操作数。
&
是按位 AND 运算符,|
是按位 OR 运算符。It means the left operand and the right operand are always evaluated.
&
is the bitwise AND operator and|
is the bitwise OR operator.& ---->用于按位与,即逐位
类似地,
| --->习惯 OR 按位
当你发现任何 python 问题时,尝试使用 python.org,它很有帮助
& ----> Used to AND bitwise i.e. bit by bit
similarly,
| ---> used to OR bitwise
Whenevr you find any python problem, try to use python.org, its helpful