开发者

printing the instance in Python

class Complex: def init(self, realpart, imagpa开发者_运维技巧rt): 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?


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.


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

inst = Complex(3,2)

inst.dosomething()


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜