i have done this in c++ but i am trying it to python and have difficulties.I did this code:
class mycomplex:
def __init__(self,real=None,imag=None):
self.real=real
self.imag=imag
def read_data(self):
self.real=input("Give the real part :")
self.imag=input("Give the imag part :")
def addition(self,complex):
return mycomplex(self.real+complex.real,self.imag+complex.imag)
def __str__(self):
return ("{0} {1} {2} {3}{4}".format("The complex is : ",self.real,"+",self.imag,"j"))
if __name__=="__main__":
a=mycomplex()
b=mycomplex()
a.read_data()
b.read_data()
print(a)
print(b)
c=a.addition(b)
print(c)
1) First of all it doesn’t work because i have in the init method 2 arguments and when i try to create an instance with a=mycomplex() it gives me an error of course.Can i handle this in some way without changing the init ?
2) In order for me to understand i want to use the addition method with 2 ways like i say in the code.It will help me i think.It’s different to say a.addition() and c=a.addition(b).
3) If you have any better suggestions from implementing the above,please say it.I think you understand what i am trying to show you.
Thank you!
1) yes you can make it work by using default values:
the default values specified in the function signature will be used in place of the missing arguments.
2) i do not understand your first way of writing an addition: when you write
a.addition(), what are you adding toa?the second way (
a.addition(b)) is pretty clear, but you need to change the way you defineaddition():