1

Possible Duplicate:
Python __str__ and lists

What is the cause when python prints the address of an object instead of the object itself?

for example the output for a print instruction is this:

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

My code looks like this:

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

I have a Person class as well, with a get_personID() function. After I have added some elements and try to print them using get_all(), it returns the above line, instead of the persons I have added.

Community
  • 1
  • 1
user1796659
  • 79
  • 1
  • 1
  • 10

2 Answers2

3

You are looking at the repr() representation of a custom class, which by default include the id() (== memory address in CPython).

This is the default used when printing a list, any contents are included using the representation:

>>> 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>]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Python calls for every list item the repr() output of each list item.

See Python __str__ and lists

Community
  • 1
  • 1