New course! Every coder should learn Generative AI!
Try a free lesson+ 1
im getting a type error and idk how to fix it
class Complex: def __init__(self,real='',imaginary='_'): if(real=='' and imaginary==''): self.real=int(input("Enter real part = ")) self.imaginary=int(input("Enter imaginary part = ")) else: self.real=real self.imaginary=imaginary def _add_(self,other): real=self.real+other.real imaginary=self.imaginary+other.imaginary s3=Complex(real,imaginary) return s3 def _sub_(self,other): real=self.real-other.real imaginary=self.imaginary-other.imaginary s3=Complex(real,imaginary) return s3 def _repr_(self): return("Real part = {}, Imaginary part = {}".format(self.real,self.imaginary)) a=Complex() b=Complex() c=a+b print(a) print(b) print(c)
10 Answers
0
class Complex:
def __init__(self,real='',imaginary=''):
if(real=='' and imaginary==''):
self.real=int(input("Enter real part = "))
self.imaginary=int(input("Enter imaginary part = "))
else:
self.real=real
self.imaginary=imaginary
def __add__(self,other):
real=self.real+other.real
imaginary=self.imaginary+other.imaginary
s3=Complex(real,imaginary)
return s3
def __sub__(self,other):
real=self.real-other.real
imaginary=self.imaginary-other.imaginary
s3=Complex(real,imaginary)
return s3
def __repr__(self):
return("Real part = {}, Imaginary part = {}".format(self.real,self.imaginary))
a=Complex()
b=Complex()
c=a+b
print(a)
print(b)
print(c)
+ 1
Try putting double underscores around add and sub (so __add__ and __sub__). Magic Methods require double underscores. Same with repr.
+ 1
i removed the underscores from the add, sub and repr functions. its running but im getting an error on line 26 which is "c=a+b"
This is the updated code:
class Complex:
def __init__(self,real='',imaginary=''):
if(real=='' and imaginary==''):
self.real=int(input("Enter real part = "))
self.imaginary=int(input("Enter imaginary part = "))
else:
self.real=real
self.imaginary=imaginary
def add(self,other):
real=self.real+other.real
imaginary=self.imaginary+other.imaginary
s3=Complex(real,imaginary)
return s3
def sub(self,other):
real=self.real-other.real
imaginary=self.imaginary-other.imaginary
s3=Complex(real,imaginary)
return s3
def repr(self):
return("Real part = {}, Imaginary part = {}".format(self.real,self.imaginary))
a=Complex()
b=Complex()
c=a+b
print(a)
print(b)
print(c)
0
Why did you remove them? I said to put double underscores.
0
i did put double underscores, but i was getting the same error and the output was not asking or an input. but when i removes them and ran it again, it asked for the output and then showed the error
0
OOHHH nvm i got it
0
Thanks for your help Russ
0
Why did we add the double underscores??
0
__add__ is the Magic Method for the "+" sign. When you create classes, you might need to define behaviour between two objects. When a + b is executed, it looks to the class magic method __add__ to find out what to do.
0
Oh Okay, thanks!!