# 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)