1class Vector:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __add__(self, other):
7 return Vector(self.x + other.x, self.y + other.y)
1class GridPoint:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __add__(self, other): # Overloading + operator
7 return GridPoint(self.x + other.x, self.y + other.y)
8
9 def __str__(self): # Overloading "to string" (for printing)
10 string = str(self.x)
11 string = string + ", " + str(self.y)
12 return string
13 def __gt__(self, other): # Overloading > operator (Greater Than)
14 return self.x > other.x
15point1 = GridPoint(3, 5)
16point2 = GridPoint(-1, 4)
17point3 = point1 + point2 # Add two points using __add__() method
18print(point3) # Print the attributes using __str__() method
19if point1 > point2: # Compares using __gt__() method
20 print('point1 is greater than point2')
1def __add__(self, other):
2 if isinstance(other, self.__class__):
3 return self.x + other.x
4 elif isinstance(other, int):
5 return self.x + other
6 else:
7 raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
1class A():
2 def __init__(self, name):
3 self.name = name
4
5 # This func will define what happens when adding two obects type A
6 def __add__(self, b):
7 return (str(self.name) + " " + str(b.name))
8
9 # This func will define what happens when converting object to str
10 def __str__(self): # Requested with the print() func
11 return self.name
12
13Var1 = A('Gabriel')
14Var2 = A('Stone')
15
16Var3 = Var1 + Var2
17
18print(Var1)
19print(Var2)
20print(Var3)