educative.io

"Com" in Method Override

I am not clear on why “Com” was called in the “add” and “sub” methods.
Is self call or recursive nature necessary.

class Com:

def __init__(self,real=0,imag=0):
    self.real = real
    self.imag = imag

def __add__(self,other):
    temp = **Com**(self.real + other.real, self.imag + other.imag)
    return temp

def __sub__(self,other):
    temp = **Com**(self.real - other.real,self.imag - other.imag)
    return temp
1 Like

Hi, @Payel_Thakre!

This has been done so we get an instance of a class as our return type. Suppose we didn’t call “Com” in the “add” and “sub” methods, we would have gotten tuples instead and we would not have been able to access the real and imaginary parts using self.real and self.imaginary.

By calling “Com” in the functions, we were able to assign the newly computed real part to self.real and imaginary part to self.imag and this, in turn, provided us with a new complex number, which we can print accordingly, as done in the image given below:

Screenshot 2021-08-06 at 11.29.57 AM

1 Like