|
|
|
|
|
by mikeash
4839 days ago
|
|
It seems to me that it's a cultural problem more than anything. People know that they shouldn't take an existing, well-known method name and repurpose it for something completely different. But somehow a lot of people think it's OK to repurpose an operator to mean something completely different just because it's convenient. C++ being the classic example. << means bitshift. Just because it looks like arrows doesn't mean it's sane to repurpose it into a completely different "output this" operator. You wouldn't override "leftShift" to output stuff, so why do people do it with <<? I think it depends a lot on the languages. Operator overloading is easy and common in Python, but in my (limited) experience, it's used to create new classes which respond to existing operators with existing semantics, e.g. to make new number classes. For this, it's great. There's no particular reason the types built-in to the language should get special treatment for operators, as long as programmers can resist the temptation to be idiots. |
|
In Python, it's called "special method attributes" and they can do a lot more than just create classes. The __eq__ attribute returns a straight boolean for example in response to the "==" operator. And yes, by the way, you actually can accidentally alter attributes in the calling and callee objects if you aren't careful.