python - 添加\n 到 __repr__

标签 python

我正在尝试格式化对象的 __repr__,以便它用换行符分隔数组的每个元素。

这是类:

class Data:
    taskArray = []
    def __init__(self,units):
        self.units = units
    def __repr__(self):
        return str("Units: {0} \n{1}".format(self.units, self.taskArray))

此时会打印成这样:

Units: 4
[Element1, Element2, Element3]

我希望它打印成这样:

Units: 4
[Element1,
Element2,
Element3]

我将如何完成这个?

最佳答案

使用str.join :

>>> class Data:
...     taskArray = ["foo", "bar"]
...     def __init__(self,units):
...         self.units = units
...     def __repr__(self):
...         return "Units: {0} \n[{1}]".format(self.units, ",\n".join(repr(t) for t in self.taskArray))
... 
>>> print(Data(4))
Units: 4 
[foo,
bar]

关于python - 添加\n 到 __repr__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756163/

相关文章:

python - 如何在 Python 中按行的总和对矩阵进行升序排序?

python - 导入错误 : No module named flask. ext.httpauth

python - 元组重排Python

python - JupyterLab 3.0.16 : Exporting HTML results on "Blocking request with no referer" and "403 Blocking request from unknown origin"

python - 在Python中使用矩阵格式来计算我自己的相似度分数

Python-更改列表列表中的元素

python - 在python中使用蒙特卡洛方法

python - 在网络应用程序上使用 PyperClip

python - 如何在 Python 中使用 mysqldump 和 mysql 复制数据库?

python - 如何通过 Selenium 和 Python 使用用户代理单击 YouTube 评论中的 YouTube 链接