2013-01-13 2 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 

가 나는 get_personID() 함수뿐만 아니라, Person 클래스가 있습니다. 몇 가지 요소를 추가하고 get_all()을 사용하여 인쇄하려고하면 내가 추가 한 사람 대신 위의 줄을 반환합니다.

+0

는 일부 코드가 도움이 ... – jgr

+0

될 것 확인하고 인쇄 명령은 무엇입니까? 그 물건을 어떻게 얻었습니까? –

답변

2

기본적으로 id() (== CPython의 메모리 주소)을 포함하는 사용자 정의 클래스의 표현은 repr()입니다.

이 목록을 인쇄 할 때 사용되는 기본값은 모든 내용이 표현을 사용하여 포함되어 있습니다

>>> 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>] 
0

파이썬은리스트의 모든 항목에 대한 각 목록 항목의 에 repr() 출력을 호출합니다.

Python __str__ and lists