我想为向量编写一个类,我需要能够将列表中的整数转换为字符串并打印它们。
示例:[1,2.5] - >“<1,2.5>”
这是我提出但它不起作用,任何帮助将不胜感激。
class Vector(list):
def __init__(self,other):
assert len(other)!=0, "Invalid Input!"
for e in other:
assert type(e)==int or type(e)==float, "Invalid Input!"
list.__init__(self,other)
def __str__(self):
s = ''
for x in range (len(self)):
s + = str(self.x)
return s
使用join函数组合自身。
def __str__(self):
return "<%s>" % ", ".join(self)
Join将基本上返回由逗号和空格分隔的列表内容的字符串。然后我们将尖括号放在我们将其组合的字符串中。
使用f
-strings的另一种选择
def __str__(self):
return(f'<{super().__str__()[1:-1]}>')