What does the caret operator (^) in Python do?

前端 未结 5 1772
忘了有多久
忘了有多久 2020-11-28 04:19

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
>         


        
5条回答
  •  孤独总比滥情好
    2020-11-28 05:18

    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)
     in ()
    ----> 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
    

提交回复
热议问题