Why/When in Python does `x==y` call `y.__eq__(x)`?

You’re missing a key exception to the usual behaviour: when the right-hand operand is an instance of a subclass of the class of the left-hand operand, the special method for the right-hand operand is called first. See the documentation at: http://docs.python.org/reference/datamodel.html#coercion-rules and in particular, the following two paragraphs: For objects x and y, first x.__op__(y) … Read more

Why does Python have an __ne__ operator method instead of just __eq__?

SQLAlchemy is a great example. For the uninitiated, SQLAlchemy is a ORM and uses Python expression to generate SQL statements. In a expression such as meta.Session.query(model.Theme).filter(model.Theme.id == model.Vote.post_id) the model.Theme.id == model.VoteWarn.post_id does not return a boolean, but a object that eventually produces a SQL query like WHERE theme.id = vote.post_id. The inverse would produce … Read more

operator

The problem is that you define it inside the class, which a) means the second argument is implicit (this) and b) it will not do what you want it do, namely extend std::ostream. You have to define it as a free function: class A { /* … */ }; std::ostream& operator<<(std::ostream&, const A& a);