2012-10-09 25 views
1

可能重複:
Python: How to print a class or objects of class using print()?如何在python中打印/返回一個類?

我現在有這樣的代碼:

class Track(object): 
    def __init__(self,artist,title,album=None): 
     self.artist = artist 
     self.title = title 
     self.album = album 

    def __str__(self): 
     return self.title + self.artist + self.album 

現在,當我把類似Track('Kanye West','Roses','Late Registration')到終端我得到<__main__.Track object at 0x10f3e0c50>我怎樣才能得到它返回或打印該地點的價值?

我是新來的編程,尤其是新的'面向對象編程',所以我的問題是什麼是一個類?我如何在一個類中定義一個函數?

+0

嘗試'str(Track('Kanye West','Roses','Late Registration'))' –

+3

搜索優先:http://stackoverflow.com/questions/1535327/python-how-to-print-a -class-or-objects-of-class-using-print –

+0

我嘗試過搜索,但我仍然有點困惑,我想我正在尋找更多日常用語的解釋。 – iamtesla

回答

9

您應該定義__repr__方法:

class Track(object): 

    ... 

    def __repr__(self): 
     return ('Track(artist=%s album=%s title=%s)' 
       % (repr(self.artist), repr(self.title), repr(self.album))) 

現在你可以看到在終端對象的表示:

>>> Track('Kanye West','Roses','Late Registration') 
Track(artist='Kanye West' album='Roses' title='Late Registration') 

注意__str____repr__方法之間的區別:

  • __str__需要將對象轉換爲字符串。調用:str(obj)
  • __repr__ - 用於人類可讀的可視化。呼喚:repr(obj)

當你投入到終端obj,蟒蛇自動調用repr功能。但是如果你使用print obj表達,蟒蛇調用str功能:

>>> obj 
...repr of obj here... 
>>> print obj 
...str of obj here... 

更多信息請參見doc

+2

'__repr__'應該創建一個有效的Python表達式來重新創建對象。所以你應該改變你的格式,或者改用'__str__'。請參閱http://docs.python.org/reference/datamodel.html#object.__repr__ – Achim

+0

你是對的,修復。 – defuz

+1

雖然這會產生所需的結果,但這可能不是OP所需要的,並且不在OP的範圍內,顯然是有限的Python技能組合 - 我想他只是想知道如何打印答案,一個簡單的解決方案(如我的)只是「打印」 –

3

你的代碼很好,但你忘記了一些東西。

比方說你有這個類:

class Bob(): 
    def __init__(self, hobby): 
     self.hobby = hobby 

在控制檯,你會做出鮑勃類這樣的嗜好:

a = Bob("skiing") 

然後讓Bob的愛好,你可以這樣做:

print a.hobby 

現在 - 回到你的問題,你沒有Track('Kanye West','Roses','Late Registration')

您創建了一個對象,但您沒有將該對象分配給一個變量。所以你的結果是對象本身......你可以簡單地打印該對象,這將調用__str__方法。所以...

print Track('Kanye West','Roses','Late Registration') 

會工作,但如果你想要做得更好一點。(例如)

a = Track('Kanye West','Roses','Late Registration') 
print a.title 
print a.artist 
print a.album 
0

如果你需要做只是爲了調試運行宗旨,以檢查你的對象的內在價值,你可以做這樣的

Track('Kanye West','Roses','Late Registration').__dict__ 

它會告訴你內部數據表示爲Python字典

+0

而不是顯式訪問'__dict__',我認爲它使用'vars(name_of_object)'看起來更清潔一些。 – DSM