views:

61

answers:

4

Hello! With this code:

class Complex:
    def __init__(self, realpart, imagpart):
        self.real = realpart
        self.imag = imagpart
        print self.real, self.imag

I get this output:

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

But why does he print the last line?

+3  A: 

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

muckabout
+6  A: 

You running the code from an interactive python prompt, which prints out the result of any statements, unless it is None.

Try it:

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

So your call to Complex(3,2) is creating an object, and python is printing it out.

Douglas Leeder
+1  A: 

What you want is to define __str__(self) and make it return a string representation (not print one).

hasen j
+3  A: 

Because class constructor always return instance, then you could call its method after that

inst = Complex(3,2)

inst.dosomething()
S.Mark