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")返回NotImplementedbool(NotImplemented)是True,所以bool(None.__eq__("a"))就等于True。这种bool(NotImplemented)的特殊情况,值得注意一下。