简体   繁体   English

在python中,如何使用__str__逐行返回列表中的元素

[英]In python, how to use __str__ to return elements in a list, line by line

I have a class Numberlist which takes a list of numbers. 我有一个Numberlist类,它包含一个数字列表。

class Numberlist:
    def __init__(self,number):
        self.number=number
    def __str__(self):
        for i in self.number:
            print(i)
        return '{}'.format('')

I want to display the list of numbers in the following format when printing a object. 我想在打印对象时以以下格式显示数字列表。

x = Numberlist([1,2,3,4,5,6])
print(x)
print("done printing")
1 
2 
3
4
5
6

done printing

My attempt is not correct because there is an empty line at the end of the output. 我的尝试不正确,因为输出末尾有一个空行。 I am stuck because __str__ requires you to return string type element. 我陷入困境是因为__str__要求您返回字符串类型元素。

What you're seeing 您所看到的

You're seeing an extra newline because you're printing every element in the list in your __str__ function then printing the value returned from __str__ : namely, "" . 您看到了一个额外的换行符,因为您正在打印__str__函数列表中的每个元素,然后打印从__str__返回的值:即"" Unless you designate end in print , it defaults to a newline, so you're effectively printing "\\n" . 除非您指定print end ,否则它默认为换行符,因此您实际上是在打印"\\n"

What you (probably) want to do 您(可能)想做什么

You probably want to print just the stringified representation of your class. 您可能只想打印类的字符串表示形式。 If that's each element newline-delimited, I'd define __str__ in the following way: 如果那是每个以换行符分隔的元素,我将通过以下方式定义__str__

def __str__(self):
    return '\n'.join(map(str, self.number))

This will put a newline between the string representation of each element in self.number and return that single string. 这将在self.number中每个元素的字符串表示形式之间放置换行符,并返回该单个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM