[Tutor] A complex number class, making a class instance of same class inside one of its methods

Manprit Singh manpritsinghece at gmail.com
Wed Aug 25 13:50:15 EDT 2021


Dear sir,

I have written a class Complex_num, from which i can set the values of real
and imaginary part of complex number(setvalue) , and compare the magnitude
of two instances of this class(__gt__()) . Add real and imaginary parts of
two instances of this class(__add__()) and print the values of instance
objects with __str__().

class Complex_num:

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

    def setvalue(self, real, imag):
        self.real = real
        self.imag = imag

    def __gt__(self, com_num):
        c1 = (self.real**2 + self.imag**2)**0.5
        c2 = (com_num.real**2 + com_num.imag**2)**0.5
        return c1 > c2

    def __add__(self, com_num):
        temp = Complex_num()
        rpart = self.real + com_num.real
        ipart = self.imag + com_num.imag
        temp.setvalue(rpart, ipart)
        return temp

    def __str__(self):
        sign ="+" if self.imag >= 0 else ""
        com = "("+str(self.real)+sign +str(self.imag)+"j)"
        return com

x = Complex_num()
x.setvalue(4, 1)
y = Complex_num()
y.setvalue(4, -5)
print(x)  - returns (4+1j)
print(y) - returns (4-5j)
x > y returns False
print(x+y) returns (8-4j)

The answers are correct , but i have a question :

Can we call the class inside any method of the class ? If I need an
instance object of the class inside one of the methods of the same class.

In the above given class  Complex_num, inside def__add__() , i have made an
instance object temp, The idea is after finding the sum of real and
imaginary parts of instance objects x & y inside __add__(), I have set the
instance variables of the instance object temp with this sum of real and
imaginary parts, returning this temp will cause print(x+y) to print the sum
of real and imaginary parts of x& y.due to __str__().

Regards
Manprit Singh


More information about the Tutor mailing list