Operator Overloading
PronunciationOP-er-ay-ter OH-ver-LOH-ding
Definition
Operator overloading lets your own class decide what operators such as +, == or < mean for its objects, by defining special methods.
Where you hear it
In Python and C++ classes, math or money types, and reviews of custom value objects.
Examples
Implementing
__add__lets you writeprice_a + price_bfor Money objects.Compare two points with
==because the class defines equality.The Vector class defines __add__, so two vectors can be added with the plus sign.
Common mistake
Giving an operator a surprising meaning. Keep it natural: + should combine things, not trigger side effects.
Don't confuse with
A normal method such as add(). Overloading makes the operator itself work on your objects.
Say it at work
- In a meeting or chat
Overload
+so adding two amounts of the same currency just works. - In an email or ticket
Return
NotImplementedfor types the operator doesn't support.
Keep exploring
More in Programming Fundamentals