8 7-OperatorOverloading
8 7-OperatorOverloading
ipynb - Colab
Operator overloading allows you to define the behavior of operators (+, -, *, etc.) for custom objects. You achieve this by overriding specific
magic methods in your class.
__gt__
'''
'\n__add__(self, other): Adds two objects using the + operator.\n__sub__(self, other): Subtracts two objects using the -
operator.\n__mul__(self, other): Multiplies two objects using the * operator.\n__truediv__(self, other): Divides two objects using the
/ operator.\n__eq__(self, other): Checks if two objects are equal using the == operator.\n__lt__(self, other): Checks if one object is
less than another using the < operator.\n\n'
def __add__(self,other):
return Vector(self.x+other.x,self.y+other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(v1+v2)
print(v1-v2)
print(v1*3)
Vector(6, 8)
Vector(-2, -2)
Vector(6, 9)
https://colab.research.google.com/drive/1fokixXzej_OsRE0biBMZe97s0rWBhtvM#printMode=true 1/2
7/18/24, 10:42 AM 8.7-OperatorOverloading.ipynb - Colab
### Overloading Operators for Complex Numbers
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __repr__(self):
return f"{self.real} + {self.imag}i"
https://colab.research.google.com/drive/1fokixXzej_OsRE0biBMZe97s0rWBhtvM#printMode=true 2/2