
Python overloading operator - Add, subtract, multiply objects using arithmetic operators
Python string can be added using plus symbol as if strings were numbers. You can define addition to class object using __add__
function.
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector(x, y, z)
u = Vector(1, 2, 3)
v = Vector(4, 5, 6)
w1 = u + v
w2 = u.__add__(v)
print(w1.x, w1.y, w1.z) # 5 7 9
print(w2.x, w2.y, w2.z) # 5 7 9
Vector class is the original class and the object has 3 properties, x, y, z. This class defines __add__
method so the vector object can be added like Python number or string.
w1 and w2 are the same. The form u+v
is exactly addition!
Subtraction
__sub__
is a subtraction method that enables the object subtraction as follows.
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector(x, y, z)
def __sub__(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
u = Vector(1, 2, 3)
v = Vector(4, 7, 10)
w = v - u
print(w.x) # 3
print(w.y) # 5
print(w.z) # 7
Multiplication
__mul__
is a multiplication method. The following example shows how to define the function calculating the inner product of vectors with multiplication overriding.
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector(x, y, z)
def __sub__(self, other):
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vector(x, y, z)
def __mul__(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
u = Vector(1, 2, 3)
v = Vector(1, 1, 1)
w = v * u
print(w) # 6
Comments
Powered by Markdown