2013-01-13 51 views
2

可能重複:
Python __str__ and lists蟒紋失敗

的原因是什麼,當蟒蛇打印的對象,而不是對象本身的地址?

例如輸出打印指令是這樣的:

[< ro.domain.entities.Person object at 0x01E6BA10>, < ro.domain.entities.Person object at 0x01E6B9F0>, < ro.domain.entities.Person object at 0x01E6B7B0>] 

我的代碼如下所示:

class PersonRepository: 
    """ 
    Stores and manages person information. 
    """ 
    def __init__(self): 
     """ 
     Initializes the list of persons. 
     """ 
     self.__list=[] 

    def __str__(self): 
     """ 
     Returns the string format of the persons list. 
     """ 
     s="" 
     for i in range(0, len(self.__list)): 
      s=s+str(self.__list[i])+"/n" 
     return s 

    def add(self, p): 
     """ 
     data: p - person. 
     Adds a new person, raises ValueError if there is already a person with the given id. 
     pos: list contains new person. 
     """ 
     for q in self.__list: 
      if q.get_personID()==p.get_personID(): 
       raise ValueError("Person already exists.") 
     self.__list.append(p) 

    def get_all(self): 
     """ 
     Returns the list containing all persons. 
     """ 
     l=str(self.__list) 
     return l 

我有一個Person類爲好,用get_personID()函數。在添加了一些元素並嘗試使用get_all()打印它們之後,它將返回上面的行,而不是我添加的人。

+0

一些代碼將是有益的... – jgr

+0

,什麼是你的打印命令?你是如何獲得這個物體的? –

回答

2

您正在查看自定義類的repr()表示,默認情況下,該類包含id()(== CPython中的內存地址)。

這是打印列表時使用的默認,任何內容所使用的表示包括:

>>> class CustomObject(object): 
...  def __str__(self): 
...   return "I am a custom object" 
... 
>>> custom = CustomObject() 
>>> print(custom) 
I am a custom object 
>>> print(repr(custom)) 
<__main__.CustomObject object at 0x10552ff10> 
>>> print([custom]) 
[<__main__.CustomObject object at 0x10552ff10>]