本文主要介绍Python3中类的__eq__使用的特殊情况,None.__eq__(“a”)值应为NotImplemented,有些情况进行比较值为True,下面具体看一下。

1、__eq__方法返回NotImplemented的情况

None.__eq__('a')

通过None直接调用__eq__方法返回的是NotImplemented(1).__eq__('a')'a'.__eq__(1)也返回NotImplemented

2、示例代码 

class A:
    def __eq__(self, other):
        print('A.__eq__')
        return NotImplemented
class B:
    def __eq__(self, other):
        print('B.__eq__')
        return NotImplemented
class C:
    def __eq__(self, other):
        print('C.__eq__')
        return True
a = A()
b = B()
c = C()
print(a == b)
# A.__eq__
# B.__eq__
# False
print(a == c)
# A.__eq__
# C.__eq__
# True
print(c == a)
# C.__eq__
# True

3、结论

None.__eq__("a")等于True的情况,由于None.__eq__("a")返回NotImplemented
bool(NotImplemented)True,所以bool(None.__eq__("a"))就等于True。这种bool(NotImplemented)的特殊情况,值得注意一下。

推荐文档