脱字号 (^) 运算符的作用是什么?
我今天在 python 中遇到了插入符运算符并尝试了一下,得到了以下输出:
>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>>> 8^0
8
>>> 7^1
6
>>> 7^2
5
>>> 7^7
0
>>> 7^8
15
>>> 9^1
8
>>> 16^1
17
>>> 15^1
14
>>>
它似乎基于 8,所以我猜测是某种字节操作?我似乎找不到太多关于这个搜索网站的信息,除了它对浮点数的行为很奇怪之外,有人有这个运算符的链接吗?或者你能在这里解释一下吗?
I ran across the caret operator in python today and trying it out, I got the following output:
>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>>> 8^0
8
>>> 7^1
6
>>> 7^2
5
>>> 7^7
0
>>> 7^8
15
>>> 9^1
8
>>> 16^1
17
>>> 15^1
14
>>>
It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find much about this searching sites other than it behaves oddly for floats, does anybody have a link to what this operator does or can you explain it here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一般来说,符号
^
是的 infix 版本>__xor__
或__rxor__
方法。无论放置在符号右侧和左侧的数据类型都必须以兼容的方式实现此功能。对于整数,这是常见的 XOR 运算,但例如,对于float
类型和int
类型,没有内置的函数定义>:Python 的一个巧妙之处是您可以在自己的类中重写此行为。例如,在某些语言中,
^
符号表示求幂。您可以通过这种方式做到这一点,就像一个例子:然后这样的事情就会起作用,现在,仅对于
Foo
的实例,^
符号表示求幂。Generally speaking, the symbol
^
is an infix version of the__xor__
or__rxor__
methods. Whatever data types are placed to the right and left of the symbol must implement this function in a compatible way. For integers, it is the commonXOR
operation, but for example there is not a built-in definition of the function for typefloat
with typeint
:One neat thing about Python is that you can override this behavior in a class of your own. For example, in some languages the
^
symbol means exponentiation. You could do that this way, just as one example:Then something like this will work, and now, for instances of
Foo
only, the^
symbol will mean exponentiation.当您使用
^
运算符时,方法__xor__
被调用。a^b
相当于a.__xor__(b)
。此外,
a ^= b
相当于a = a.__ixor__(b)
(其中__xor__
用作__ixor__
通过使用^=
隐式调用,但不存在)。原则上,
__xor__
所做的事情完全取决于它的实现。 Python 中的常见用例有:演示:
演示:
解释:
When you use the
^
operator, behind the curtains the method__xor__
is called.a^b
is equivalent toa.__xor__(b)
.Also,
a ^= b
is equivalent toa = a.__ixor__(b)
(where__xor__
is used as a fallback when__ixor__
is implicitly called via using^=
but does not exist).In principle, what
__xor__
does is completely up to its implementation. Common use cases in Python are:Demo:
Demo:
Explanation:
它是按位XOR(异或)。
当且仅当其参数不同(一个是
True
,另一个是False
)时,它的计算结果为True
。演示:
解释你自己的一个例子:
这样想一下:
It's a bitwise XOR (exclusive OR).
It evaluates to
True
if and only if its arguments differ (one isTrue
, the other isFalse
).To demonstrate:
To explain one of your own examples:
Think about it this way:
它根据需要调用对象的 __xor__() 或 __rxor__() 方法,该方法对于整数类型执行按位异或。
It invokes the
__xor__()
or__rxor__()
method of the object as needed, which for integer types does a bitwise exclusive-or.这是一个逐位异或。二元按位运算符记录在Python 语言参考的第 5 章。
It's a bit-by-bit exclusive-or. Binary bitwise operators are documented in chapter 5 of the Python Language Reference.