Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you overload the caret (^) operator in python

I need to override the caret behaviour in a class, but I'm not sure which operator overload applies to it. For example:

class A: 
    def __init__(self, f):
        self.f = f
    def __caret__(self, other):
        return self.f^other.f

print A(1)^A(2)

This code errors with:

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

How can I construct the class so that I can control the behaviour?

like image 822
ninhenzo64 Avatar asked Dec 05 '22 16:12

ninhenzo64


2 Answers

Define A.__xor__() or A.__rxor__().

like image 112
Ignacio Vazquez-Abrams Avatar answered Dec 08 '22 00:12

Ignacio Vazquez-Abrams


The ^ is an xor operator. You can overload it with the __xor__ method.

For example

>>> class One:
...     def __xor__(self, other):
...             return 1 ^ other
... 
>>> o = One()
>>> o ^ 1
0
>>> o ^ 0
1
like image 37
tlikarish Avatar answered Dec 08 '22 00:12

tlikarish