-1
class ComplexNum:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def real(self):
        return self.x
    def imag(self):
        return self.y
    def get_r(self):
        return math.sqrt(self.y*self.y + self.x*self.x)
    def sqrt(self):
        complexA = cmath.sqrt(complex(self.x, self.y))
        A = ComplexT(complexA.real, complexA.imag)
        return A
    def sub(self, complexNum):
        a = complex(self.x,self.y)
        b = complex(complexNum.x, complexNum.y)
        c = a - b
        return ComplexT(c.real, c.imag)

I am a bit confused about the concept of getters and setters at the moment, What are the methods considered as? getters or setters or something else?

2 Answers2

3

You only have getters and instance methods here. Nothing is updating self.? = ? outside the constructor

That being said, if you are just doing return self.?, then it's not really necessary as you can access complex_num_instance.? directly without any function calls

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
2

the methods shown in your code above would be 'getters' as they 'get' some sort of value once they are ran. Notice how they all return something.

IE: number = complexnum.real()

the 'real' method would return self.x and store it in the 'number' variable. the number variable GOT a value from the real method. One convention that is commonly used is to name these methods with the prefix of 'get'. So this method would become 'get_real(self)'

A setter does kind of the opposite. A setter will 'set' a value.

IE: If we wanted to SET the value of self.x you could have a method like this. complexnum.set_x(3). This would set x's value to 3.

Here is your code retyped using these ideas:

# Code 
class ComplexNum:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def get_real(self):
        return self.x
    def get_imag(self):
        return self.y
    def get_r(self):
        return math.sqrt(self.y*self.y + self.x*self.x)
    def get_sqrt(self):
        complexA = cmath.sqrt(complex(self.x, self.y))
        A = ComplexT(complexA.real, complexA.imag)
        return A

    # Adding a setter
    def set_x(self, value):
        self.x = value
General Grievance
  • 4,555
  • 31
  • 31
  • 45