[英]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.