4

我需要覆盖类中的插入符号行为,但我不确定哪个运算符重载适用于它。例如:

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

print A(1)^A(2)

此代码错误:

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

如何构建类以便我可以控制行为?

4

2 回答 2

13

定义A.__xor__()A.__rxor__()

于 2012-05-15T23:57:51.930 回答
3

^ 是一个异或运算符。__xor__您可以使用该方法重载它。

例如

>>> class One:
...     def __xor__(self, other):
...             return 1 ^ other
... 
>>> o = One()
>>> o ^ 1
0
>>> o ^ 0
1
于 2012-05-16T00:03:39.813 回答