It’s best to return NotImplemented in magic method(e.g. __eq__, __ne__, etc), see here for details.
1234567891011121314151617181920212223242526
# example.pyclassA(object):def__init__(self,value):self.value=valuedef__eq__(self,other):ifisinstance(other,A):print('Comparing an A with an A')returnother.value==self.valueifisinstance(other,B):print('Comparing an A with a B')returnother.value==self.valueprint('Could not compare A with the other class')returnNotImplementedclassB(object):def__init__(self,value):self.value=valuedef__eq__(self,other):ifisinstance(other,B):print('Comparing a B with another B')returnother.value==self.valueprint('Could not compare B with the other class')returnNotImplemented
a is instance of ClassA, and b is instance of ClassB, if we invoke a == b, we will get the result, True or False, but if we invoke b == a, we will also get the result! Because of we return NotImplemented in Class B’s __eq__ method, runtime could invoke Class A’s __eq__, that method can compare A and B.