^ 在 python 中做什么?

问题描述 投票:0回答:2

我在 python 中偶然发现了

^
运算符,但我不明白它的作用。
我在网上找不到任何相关信息。

python operators
2个回答
2
投票

Python 中的 ^ 运算符称为按位异或运算符。 它对两个操作数执行二进制 XOR 运算并返回结果。

假设你有两个整数a和b,你想对它们进行异或运算。如果两个整数中对应的位不同,异或运算返回 1,如果相同则返回 0。

a ^ b = 6 ^ 3 = 5

a = 110
b = 011
---------
    101 = 5

0
投票

就像大多数运算符一样,它会按照操作数的要求去做。例如:

class C:
    def __xor__(self, other):
        return 'whatever you want'

print(C() ^ C())

输出:

whatever you want

在线试用!

© www.soinside.com 2019 - 2024. All rights reserved.