3 ms·
Yup, that's true. In Python, generally if you want to only compare equal to the same type, you would use the NotImplemented value to implement: class MyCla
by bobbiechen 6y ago
Yup, that's true. In Python, generally if you want to only compare equal to the same type, you would use the NotImplemented value to implement:
class MyClass:
def __eq__(self, other):
if not isinstance(other, MyClass):
return NotImplemented
else:
# whatever your comparison is
When NotImplemented is returned, there is a fallback sequence described in https://docs.python.org/3/library/numbers.html#implementing-the-arithmetic-operations https://docs.python.org/3/library/numbers.html#implementing-... - where basically, in the expression `A == B`, if `A.__eq__(B)` returns NotImplemented, then `B.__eq__(A)` is checked as well (falling back to an `is` identity comparison if both return NotImplemented).
This is neat because it allows you to define a class B that can compare equal to an existing class A with the expression A == B, even though class A has no knowledge of B.