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?
Define A.__xor__() or A.__rxor__().
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With