2011-08-08 79 views
4

你能解釋爲什麼'hello world'不被返回到下面嗎?我需要修改什麼才能在被調用時正確表達?謝謝。python類的簡單實例

>>> class MyClass: 
...  i=12345 
...  def f(self): 
...   return 'hello world' 
...  
>>> x=MyClass() 
>>> x.i 
12345 
>>> x.f 
<bound method MyClass.f of <__main__.MyClass instance at 0x060100F8>> 

回答

5

當在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 
+1

徹底的答案是一個很好的答案,值得花時間。 – cwallenpoole

+0

非常感謝,@cwallenpoole!這是一個徹底的答覆。我非常感謝你的明確解釋。 – nlper

+1

@niper - 順便說一下,cwallenpoole的回答(在我看來)比我的回答更清晰,更徹底。不要因爲我碰巧早點得到更多選票而感到需要標記我的權利!標記哪一個最能幫助你「接受」。 :) –

8

f是一種方法,所以你需要調用它。即x.f()

這是沒有什麼不同,如果你定義一個函數沒有類:

def f(): 
    return 'something' 

如果你只是參考f,你會得到函數本身

print f 

產量<function f at 0xdcc2a8>,同時

print f() 

收益率"something"

+0

非常感謝@Joe Kington!我正在閱讀一個教程,並沒有提到。再次感謝。 – nlper