當在REPL(或Python控制檯或其它)中時,總是會打印最後一條語句返回的值。如果它僅僅是一個值的值將被打印出來:
>>> 1
1
如果它是一個任務,然後什麼都不會被打印:
>>> a = 1
不過,看這個:
>>> a = 1
>>> a
1
好的,在上面的代碼中:
>>> x=MyClass()
>>> x # I'm adding this :-). The number below may be different, it refers to a
# position in memory which is occupied by the variable x
<__main__.MyClass instance at 0x060100F8>
因此,x的值是MyClass位於內存中的一個實例。
>>> x.i
12345
x.i的值是12345,因此它將如上打印。
>>> x.f
<bound method MyClass.f of <__main__.MyClass instance at 0x060100F8>>
F值是x的方法(這就是它意味着有def
在前面的東西,它是一種方法)。現在,因爲它是一種方法,讓我們加入後的()
叫它:
>>> x.f()
'hello world'
在變量x的MyClass的實例用f方法返回的值是「世界你好」!可是等等!有引號。我們通過使用print
功能擺脫它們:
>>> print(x.f()) # this may be print x.f() (note the number of parens)
# based on different versions of Python.
hello world
徹底的答案是一個很好的答案,值得花時間。 – cwallenpoole
非常感謝,@cwallenpoole!這是一個徹底的答覆。我非常感謝你的明確解釋。 – nlper
@niper - 順便說一下,cwallenpoole的回答(在我看來)比我的回答更清晰,更徹底。不要因爲我碰巧早點得到更多選票而感到需要標記我的權利!標記哪一個最能幫助你「接受」。 :) –