这是一个小重现 - 类 A 和 B 完全相同,但为反射右移运算符实现了 dunder 方法。因此,x >> y
预计会解析为 y.__rrshift__(x)
。
class A:
def __init__(self, x):
self.x = x
def __rrshift__(self, other):
return self.__class__(self.x + other.x)
class B:
def __init__(self, x):
self.x = x
def __rrshift__(self, other):
return self.__class__(self.x + other.x)
但是,dunder 方法不适用于同一类的实例。
A(1) >> A(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'A' and 'A'
虽然它适用于来自不同类的实例。
A(1) >> B(2)
<__main__.B object at 0x7f6ca8294f40>
这真是令人惊讶。这似乎也是其他反射运算符的常见行为(例如,radd
)。这不起作用有什么原因吗?
最佳答案
作为doc states ,当操作数不同类型时有效
These functions are only called if the left operand does not support the corresponding operation and the operands are of different types
看来您只需要在两个类中 __rshift__
(仅在 A 中对您的示例有效)
def __rshift__(self, other):
return self.__class__(self.x + other.x)
关于python - 反射 dunder 方法不适用于相同类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71131434/