Implement a class in Python representing complex numbers, with addition, subtraction, etc.
We will create a class namedComplexNumberto represent complex numbers. A complex number consists of a real part and an imaginary part. We will implement addition and subtraction operations.
Example
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)
def __str__(self):
return f"{self.real} + {self.imaginary}i"
# Example usage
c1 = ComplexNumber(3, 4)
c2 = ComplexNumber(1, 2)
print("c1 + c2 =", c1 + c2)
print("c1 - c2 =", c1 - c2)
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
def __sub__(self, other):
return ComplexNumber(self.real - other.real, self.imaginary - other.imaginary)
def __str__(self):
return f"{self.real} + {self.imaginary}i"
# Example usage
c1 = ComplexNumber(3, 4)
c2 = ComplexNumber(1, 2)
print("c1 + c2 =", c1 + c2)
print("c1 - c2 =", c1 - c2)
Code explanation:
__init__method is used to initialize the real and imaginary parts of the complex number.__add__method implements the addition operation of complex numbers, returning a newComplexNumberobject.__sub__method implements the subtraction operation of complex numbers, returning a newComplexNumberobject.__str__method is used to convert the complex number object into a string form, making it easy to print.
Output result:
c1 + c2 = 4 + 6i c1 - c2 = 2 + 2iOther extensions
Python3 Examples