[英]How do you overload the caret (^) operator in python
我需要重写类中的插入符号行为,但是我不确定哪个运算符重载适用于它。 例如:
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'
如何构造该类,以便可以控制行为?
定义A.__xor__()
或A.__rxor__()
。
^是一个xor运算符。 您可以使用__xor__
方法重载它。
例如
>>> class One:
... def __xor__(self, other):
... return 1 ^ other
...
>>> o = One()
>>> o ^ 1
0
>>> o ^ 0
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.