Is there a way in Python to find the differences between two objects of the same type, or between two objects of any type? By differences I mean the value of one of their properties is different, or one object has a property that the other doesn't. So for example:
dog.kingdom = 'mammal'
dog.sound = 'bark'
cat.kingdom = 'mammal'
cat.sound = 'meow'
cat.attitude = 'bow to me'
In this example, I'd want to know that the sound
property is different, and the attitude
property is only in cat
.
The use case for this is I'm trying to override some default behavior in a library, and I'm setting up an object different than the library is but I don't know what.
Comparing Equality With the Python == and !=Use the equality operators == and != if you want to check whether or not two objects have the same value, regardless of where they're stored in memory.
Use the == operator to test if two variables are equal.
print(dog.__dict__.items() ^ cat.__dict__.items())
Result:
{('attitude', 'bow to me'), ('sound', 'meow'), ('sound', 'bark')}
For set-like objects, ^
is the symmetric difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With