The following class starts to define a Complex number as two numeric (int or float) values, which specify the real and imaginary parts of the Complex number. For example, we can write x = Complex(1,2) to represent the complex number 1+2i (with real part 1 and imaginary part 2) and y = Complex (2,-3) to represent the complex number 2-3i (with real part 2 and imaginary part -3). In the Complex class below, overload (a) the method called by the repr function, producing the standard result (b) the method called by the str function: the correct sign (+ or -) must appear between the real and imaginary parts: for x and y above, str(x) returns '1+2i' and str(y) returns '2-3i'. For Complex(0,0) it returns '0+0i' (c) the addition operator: we can compute the sum of two complex numbers or the sum of a complex number and an int or float (these two types are pure real: each has 0 as its imaginary part) by adding the real parts of each and adding the imaginary parts; 2+3i plus 1+2i is 3+5i; likewise, 2+3i plus 1 (or 1 plus 2+3i) is 3+3i. For any other type of operands, + should raise a TypeError with an appropriate error message. class Complex: # Assume this method initializes the two attributes of a Complex object def __init__(self,real,imaginary): self.r = real self.i = imaginary # overload the method called by repr # overload the method called by str # overload + allowing Complex + Complex, Complex + int, int + Complex, # Complex + float, and float + Complex
The following class starts to define a Complex number as two numeric (int or float) values, which specify the real and imaginary parts of the Complex number. For example, we can write x = Complex(1,2) to represent the complex number 1+2i (with real part 1 and imaginary part 2) and y = Complex (2,-3) to represent the complex number 2-3i (with real part 2 and imaginary part -3).
In the Complex class below, overload
(a) the method called by the repr function, producing the standard result
(b) the method called by the str function: the correct sign (+ or -) must appear between the real and imaginary parts: for x and y above, str(x) returns '1+2i' and str(y) returns '2-3i'. For Complex(0,0) it returns '0+0i'
(c) the addition operator: we can compute the sum of two complex numbers or the sum of a complex number and an int or float (these two types are pure real: each has 0 as its imaginary part) by adding the real parts of each and adding the imaginary parts; 2+3i plus 1+2i is 3+5i; likewise, 2+3i plus 1 (or 1 plus 2+3i) is 3+3i. For any other type of operands, + should raise a TypeError with an appropriate error message.
class Complex:
# Assume this method initializes the two attributes of a Complex object def __init__(self,real,imaginary):
self.r = real self.i = imaginary
# overload the method called by repr # overload the method called by str
# overload + allowing Complex + Complex, Complex + int, int + Complex, # Complex + float, and float + Complex
Step by step
Solved in 5 steps with 2 images