I needed to compare two instances of the same class, and determine what attribute has changed.
Comparing two objects is a pretty common task, and regardless of the language you're using, the first reflex would be to use something like this :
if (Obj1.attr1 != Obj2.attr1)
Changelist.add((String)attr1);
if (Obj1.attr2!= Obj2.attr2)
Changelist.add((String)attr2);
if (Obj1.attr3 != Obj2.attr3)
Changelist.add((String)attr3);
This could get pretty painful if your object has too many arguments. As a matter of facts, the class I'm working with has 15 arguments. That's almost 50 lines of redundant code. Obviously that wasn't good enough for me, so I turned to the Python gods and found out about the awesome
__dict__ attribute.
Here's how my changelist is now created:
changelist = [attr for (attr, val) in obj1.__dict__.items() \
if (attr, val) not in obj2.__dict__.items()]
How would you do that in your favorite language? Show us your code :)