你如何重载python中的插入符号(^)运算符

时间:2012-05-15 23:56:57

标签: python operator-overloading caret

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

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'

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

2 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:2)

^是xor运算符。您可以使用__xor__方法重载它。

例如

>>> class One:
...     def __xor__(self, other):
...             return 1 ^ other
... 
>>> o = One()
>>> o ^ 1
0
>>> o ^ 0
1
相关问题