How can I overload operators (+, -, *, /, ... , //)
on an object in python.
Example:
a = Vector(3, 5)
b = Vector(2, 7)
print(a + b) # Output: <Vector (5.000000, 12.000000)>
print(b - a) # Output: <Vector (-1.000000, 2.000000)>
print(b * 1.3) # Output: <Vector (2.600000, 9.100000)>
print(a // 17) # Output: <Vector (0.000000, 0.000000)>
print(a / 17) # Output: <Vector (0.176471, 0.294118)>
where Vector
is the following class:
class Vector(object):
def __init__(self, x, y):
self.x = x
self.y = y
Everything in Python is an object. Every object has some special internal methods that it uses to interact with other objects. In general, these methods follow the naming convention
__action__
. Collectively, this is called the Python data model .You can overload any of these methods. This is commonly used in operator overloading in Python. Below is an example of operator overloading using the Python data model. The class
Vector
creates a simple vector of two variables. We will add appropriate support for two-vector math operations using operator overloading.Operators Table
Below are the operators that can be overloaded in classes, along with the method definitions that are required, and an example of the operator in use within an expression.
Reference: Medium - (Overloading) — Overloading Operators in Python