Printing an instance in Python

class: def init (self, realpart, imagpart): self.real = actual part self.imag = imagpart print self.real, self.imag

I am getting this output:

>>> Complex(3,2)
3 2
<__main__.Complex instance at 0x01412210>

      

But why is it printing the last line?

+2


a source to share


4 answers


Since the class constructor always returns an instance, then you can call its method after that



inst = Complex(3,2)

inst.dosomething()

      

+3


a source


You run the code from the python interactive prompt, which outputs the result of any statements if it isn't None

.

Try:



>>> 1
1
>>> 1 + 3
4
>>> "foobar"
'foobar'
>>> 

      

So your call Complex(3,2)

creates an object and python prints it out.

+5


a source


Because this is the result of the statement "Complex (3,2)". In other words, a Complex object is returned and the interactive interpreter prints the result of the previous instruction to the screen. If you try "c = Complex (3, 2)", you suppress the message.

+3


a source


You want to define __str__(self)

and make it return a string representation (don't print one).

+1


a source







All Articles