python - 反射 dunder 方法不适用于相同类型的实例

标签 python class python-class

这是一个小重现 - 类 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/

相关文章:

python - 有没有办法在 Altair 上可视化时间序列数据帧,其中变量是标题?

Python 类成员初始化

python - 使类常量的类型是它所在的类

python - 如何让 __str__ 或 __repr__ 返回当前类的名称?

python - 将 2d numpy 数组转换为列表列表

python - Datalab 到 BigQuery - 将变量值插入 SQL 中

python - linkedin API 的身份验证

java - 动态地将方法体重新分配给对象

java - 重新编译时,Matlab 看不到 java 类的变化

python:将self传递给类方法内的嵌套函数是否合法?