Comparing Objects
Explore how to compare objects in Python classes by understanding the difference between equality and identity. Learn to define special methods like __eq__ and __ne__ to customize how objects are compared using operators such as == and !=, improving class functionality.
We'll cover the following...
Comparing objects in Python
The equality (==) and inequality (!=) operators work well with Python’s built-in object types. However, when you define your own classes, == will always return False when comparing two objects.
When we talk about drawing comparison between two objects, it is important to keep in mind the distinction between equal and identical.
-
Two objects,
aandb, are equal if every part ofais the same as the corresponding part ofb. If you changea,bmight or might not change. Testing for equality requires testing all the parts. -
However, if
aandbare ...