0

I am learning about classes and objects in Python. I came across the following code:

class ComplexNumber:
    def __init__(self,r = 0,i = 0):
        self.real = r
        self.imag = i

    def getData(self):
        print("{0}+{1}j".format(self.real,self.imag))

# Create a new ComplexNumber object
c1 = ComplexNumber(2,3)

# Call getData() function
# Output: 2+3j
c1.getData()

I know that the first argument when ComplexNumber is called is c1 itself which then is assigned to self. Then in _init_, r is assigned to self.real. How does it know that the type of self is complex number. If I am not wrong, self.real or self.imag can only be assigned to only variables of type class 'complex'.

But when I print the type of self it says: <class '__main__.ComplexNumber'>

Adarsh TS
  • 193
  • 15
  • It's not quite clear what your confusion is with regards to assigning `var.real` etc… – deceze Jan 30 '20 at 13:10
  • "If I am not wrong, var.real or var.imag can only be assigned to only variables of type class 'complex'." You are wrong. – juanpa.arrivillaga Jan 30 '20 at 13:10
  • @deceze I meant `var` as a general variable. To be specific here, `self.real` and `self.imag` can only be assigned to variables of type `class 'complex'` right? But how did it know that self is a complex number. – Adarsh TS Jan 30 '20 at 13:29
  • It didn't. You can freely assign anything to any object (with exceptions). Your `ComplexNumber` class logically becomes a "complex number" because it assigns itself `real` and `imag` in its `__init__`. It doesn't have anything to do with the builtin `complex` type and Python doesn't "know" anything about your `ComplexNumber`. – deceze Jan 30 '20 at 13:30
  • `class Foo: pass; foo = Foo(); foo.bar = 'baz'` — No issues. – deceze Jan 30 '20 at 13:34
  • @deceze I totally get it now. So in `class ComplexNumber` a new object `self.real` is created. Yes, you are tight, I got confused with the builtin complex type. – Adarsh TS Jan 30 '20 at 13:37

0 Answers0