Skip to main content
 首页 » 编程设计

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

2025年05月04日12xing901022

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

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__()。