[英]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__
要求您返回字符串类型元素。
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"
。
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.