Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
complex numbers
#1
I am trying to come up with methods for addition and subtraction of complex numbers,

so that the print statement should generate something like
1+2i
1-2i

if I want to use an interval (1,2).

This is my code:

class comp_num(object):
    def __init__(self, real_1, real_2):
        self.real_1=real_1
        self.real_2=real_2
    
    def __add__(self):
        a,b=self.real_1, self.real_2
        return complex(a,b)
    
    def __sub__(self):
        a,b=self.real_1, self.real_2
        return complex(a,b).conjugate()
    
    def __repr__(self):
        return '[{},{}]'.format(self.real_1. self.real_2)
    

print(comp_num(1,2))
and this is the error I get:

Error:
runfile('C:/Users/Desktop/python ode/ex8.py', wdir='C:/Users/Desktop/python ode') Traceback (most recent call last): File "<ipython-input-807-415135f62ea4>", line 1, in <module> runfile('C:/Users/Desktop/python ode/ex8.py', wdir='C:/Users/Desktop/python ode') File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile execfile(filename, namespace) File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Desktop/python ode/ex8.py", line 28, in <module> print(comp_num(1,2)) File "C:/Users/Desktop/python ode/ex8.py", line 22, in __repr__ return '[{},{}]'.format(self.real_1. self.real_2) AttributeError: 'int' object has no attribute 'self'
Reply
#2
line 15, format() method - you have dot instead of comma between self.real_1 and self.real_2
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thank you.

It runs now but only prints [1,2].

How do I actually make sure that 1+2i and 1-2i are printed ?
Reply
#4
(May-07-2019, 12:36 PM)mcgrim Wrote: How do I actually make sure that 1+2i and 1-2i are printed ?


change your __repr__ function accordingly (i.e. to output what you want)
I think there is some confusion as it's not clear what you want to achieve
>>> complex(1, 2)
(1+2j)
>>> complex(1, 2).conjugate()
(1-2j)
>>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020