programing

파이썬에서 캐럿 연산자 (^)는 무엇을합니까?

nasanasas 2020. 8. 23. 09:18
반응형

파이썬에서 캐럿 연산자 (^)는 무엇을합니까?


나는 오늘 파이썬에서 캐럿 연산자를 발견하고 그것을 시도해 보았고 다음과 같은 출력을 얻었습니다.

>>> 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을 기반으로 한 것 같으므로 일종의 바이트 작업을 추측하고 있습니까? 수레에 대해 이상하게 작동하는 것 외에는이 검색 사이트에 대해 많이 찾을 수없는 것 같습니다.이 연산자가하는 일에 대한 링크가 있습니까? 아니면 여기에서 설명 할 수 있습니까?


비트 XOR (배타적 OR)입니다.

이 경우는 true로 결과를 사실 피연산자 (평가됩니다에)의 (단 하나).

시연하려면 :

>>> 0^0
0
>>> 1^1
0
>>> 1^0
1
>>> 0^1
1

자신의 예 중 하나를 설명하려면 :

>>> 8^3
11

다음과 같이 생각해보십시오.

1000 # 8 (이진)
0011 # 3 (이진)
---- # XOR 적용 ( '수직')
1011 # 결과 = 11 (이진)

It invokes the __xor__() or __rxor__() method of the object as needed, which for integer types does a bitwise exclusive-or.


It's a bit-by-bit exclusive-or. Binary bitwise operators are documented in chapter 5 of the Python Language Reference.


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 common XOR operation, but for example there is not a built-in definition of the function for type float with type int:

In [12]: 3 ^ 4
Out[12]: 7

In [13]: 3.3 ^ 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-858cc886783d> in <module>()
----> 1 3.3 ^ 4

TypeError: unsupported operand type(s) for ^: 'float' and 'int'

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:

class Foo(float):
    def __xor__(self, other):
        return self ** other

Then something like this will work, and now, for instances of Foo only, the ^ symbol will mean exponentiation.

In [16]: x = Foo(3)

In [17]: x
Out[17]: 3.0

In [18]: x ^ 4
Out[18]: 81.0

When you use the ^ operator, behind the curtains the method __xor__ is called.

a^b is equivalent to a.__xor__(b).

Also, a ^= b is equivalent to a = 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:

  • Symmetric Difference of sets (all elements present in exactly one of two sets)

Demo:

>>> a = {1, 2, 3}
>>> b = {1, 4, 5}
>>> a^b
{2, 3, 4, 5}
>>> a.symmetric_difference(b)
{2, 3, 4, 5}
  • Bitwise Non-Equal for the bits of two integers

Demo:

>>> a = 5
>>> b = 6
>>> a^b
3

Explanation:

    101 (5 decimal)
XOR 110 (6 decimal)
-------------------
    011 (3 decimal)

참고URL : https://stackoverflow.com/questions/2451386/what-does-the-caret-operator-in-python-do

반응형