operator overloading in 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): # Overloading + operator
return GridPoint(self.x + other.x, self.y + other.y)
def __str__(self): # Overloading "to string" (for printing)
string = str(self.x)
string = string + ", " + str(self.y)
return string
def __gt__(self, other): # Overloading > operator (Greater Than)
return self.x > other.x
point1 = GridPoint(3, 5)
point2 = GridPoint(-1, 4)
point3 = point1 + point2 # Add two points using __add__() method
print(point3) # Print the attributes using __str__() method
if point1 > point2: # Compares using __gt__() method
print('point1 is greater than point2')
Example 3: overloading methods python
class A():
def __init__(self, name):
self.name = name
# This func will define what happens when adding two obects type A
def __add__(self, b):
return (str(self.name) + " " + str(b.name))
# This func will define what happens when converting object to str
def __str__(self): # Requested with the print() func
return self.name
Var1 = A('Gabriel')
Var2 = A('Stone')
Var3 = Var1 + Var2
print(Var1)
print(Var2)
print(Var3)
Example 4: python operator overloading deal with type
def __add__(self, other):
if isinstance(other, self.__class__):
return self.x + other.x
elif isinstance(other, int):
return self.x + other
else:
raise TypeError("unsupported operand type(s) for +: '{}' and '{}'").format(self.__class__, type(other))
Example 5: python override add
class MyClass:
def __add__(self, b):
return 5 + b