Question: In this section, well write a class which represents a complex number. Note that Python already has support for complex numbers built in; for this
In this section, well write a class which represents a complex number. Note that Python already has support for complex numbers built in; for this example, were expecting you to reimplement the basic functionality from scratch. All work should go in a file called complex.py.
- Create a Complex class that initializes with two optional parameters representing the real and imaginary components, defaulting to 0 if they are not specified. Store the real and imaginary components as floats in attributes called re and im. Therefore, we should be able to do something like: a = Complex(-3, 2) b = Complex(2) print(a.re) # Should print -3.0 print(b.im) # Should print 0.0
- Implement the __repr__ and __str__ magic methods so that when we try to print out your Complex number, we get a readable representation of your complex number, exactly following the format shown below: In[1]: print(Complex(-3, 2)) Out[1]: (-3.0 + 2.0i) In[2]: print(Complex()) Out[2]: (0.0 + 0.0i) In[3]: print(Complex(3.4,-2.1)) Out[3]: (3.4 - 2.1i)
- Start by implementing addition, so that all of the following work: a = Complex(2.0, 3.0) print(a + Complex(-1.5, 2)) # (0.5 + 5.0i) print(a + 8) # (10.0 + 3.0i) print(3.5 + a) # (5.5 + 3.0i) Note that the result of the addition operation should be another Complex object. You will need to define the __add__ and __radd__ magic methods to get these to work.
- Next, implement multiplication, so that all of the following work: a = Complex(1.0, -3.0) print(a * Complex(4.0, 5.5)) # (20.5 - 6.5i) print(a * 3.5) # (3.5 - 10.5i) print(-2 * a) # (-2.0 + 6.0i)
- Implement subtraction and division in the same vein. Note that because subtraction and division are non-commutative, you should pay special attention to how you define the reverse magic methods. (Did we mention to test your code?) Note: The magic method for division is __truediv__, for legacy reasons.
use python 3.8
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
