【问题标题】:python print failure [duplicate]python打印失败[重复]
【发布时间】:2013-01-13 12:11:24
【问题描述】:

可能重复:
Python __str__ and lists

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() 打印它们之后,它返回上面的行,而不是我添加的人。

【问题讨论】:

  • 一些代码会有所帮助...
  • 你的打印命令是什么?您是如何获得该对象的?

标签: python output memory-address


【解决方案1】:

您正在查看自定义类的 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>]

【讨论】:

    【解决方案2】:

    Python 为每个列表项调用每个列表项的 repr() 输出。

    Python __str__ and lists

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-18
      • 2021-10-09
      • 2016-06-30
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      相关资源
      最近更新 更多