为什么NotImplemented没有引发TypeError?

Tur*_*ion 3 python comparison-operators python-3.x

假设我定义了一个类A,我不希望任何人写出该类的不等式而不会离开.

class A():
    def __ne__(self, other):
        return NotImplemented
print(A() != A())
Run Code Online (Sandbox Code Playgroud)

但这打印出来True并没有提出一个TypeError虽然我故意"关闭"了!=运营商?

Mar*_*ers 8

当您返回时NotImplemented,表明您不知道是否__ne__应该返回TrueFalse.

通常,Python将交换操作数; 如果a != b结果NotImplemented,它会尝试b != a.这也会失败,因为你在运营商的两边使用相同的类型.对于!=运算符,Python将回退到比较它们的内存地址,这些不一样(两个独立的实例),因此返回False.

有关do_richcompare详细信息,请参阅C函数.

TypeError()如果这是您的预期结果,您将不得不手动加注.