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)
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "({0},{1})".format(self.x, self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Point(x, y)
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))
# Operator overloading
# Overload + and += operators
class Complex_number:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, right): # binary operators must provide 2 parameters
return Complex_number(self.real + right.real,
self.imaginary + right.imaginary)
def __iadd__(self, right):
"""Overrides the += operator."""
self.real += right.real
self.imaginary += right.imaginary
return self
def __repr__(self):
return (f'({self.real}' +
(' + ' if self.imaginary >= 0 else ' - ') +
f'{abs(self.imaginary)}i)')
x = Complex_number(real = 2, imaginary = 4)
x
# (2 + 4i)
y = Complex_number(real = 5, imaginary = -1)
y
# (5 - 1i)
x + y
# (7 + 3i)
x += y
x
# (7 + 3i)
y
# (5 - 1i)
# Python program to show use of
# + operator for different purposes.
print(1 + 2)
# concatenate two strings
print("Geeks"+"For")
# Product two numbers
print(3 * 4)
# Repeat the String
print("Geeks"*4)