overloading or operator python code example
Example 1: overload operator python
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
Example 2: python operator overloading
class GridPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return GridPoint(self.x + other.x, self.y + other.y)
def __str__(self):
string = str(self.x)
string = string + ", " + str(self.y)
return string
def __gt__(self, other):
return self.x > other.x
point1 = GridPoint(3, 5)
point2 = GridPoint(-1, 4)
point3 = point1 + point2
print(point3)
if point1 > point2:
print('point1 is greater than point2')