2

重複の可能性:
Python __str__ とリスト

Python がオブジェクト自体ではなくオブジェクトのアドレスを出力するときの原因は何ですか?

たとえば、印刷命令の出力は次のようになります。

[< 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() を使用してそれらを印刷しようとすると、追加した人の代わりに上記の行が返されます。

4

2 に答える 2

2

デフォルトで(== CPython のメモリアドレス) をrepr()含むカスタムクラスの表現を見ています。id()

これは、リストを印刷するときに使用されるデフォルトであり、表現を使用してすべての内容が含まれます。

>>> 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>]
于 2013-01-13T12:14:18.780 に答える
0

Python は、すべてのリスト項目に対して、各リスト項目のrepr () 出力を呼び出します。

Python __str__ とリストを参照してください

于 2013-01-13T12:14:42.467 に答える