类型错误:无法隐式将'list'对象转换为'str

0 投票
2 回答
3577 浏览
提问于 2025-04-18 18:16

我有一个Python类:

class Athlete:
    def __init__(self,fullName,dob,times):
        self.fullName = fullName
        self.dob = dob
        self.times = times
    ##  print('times is ',times)

    def __str__(self):
        return ''.join("Athlete[fullName="+self.fullName +",dob="+self.dob+",sortedTimes="+self.sortedTimes+"]")

    def __repr__(self):
        return self.__str__()

这个类的实例被存储在一个叫做 athleteMap 的映射中,作为值。

当我执行 print(athleteMap) 时,出现了这个错误:

File "D:/Software/ws/python_ws/collections\athleteList.py", line 11, in __str__
    return ''.join("Athlete[fullName="+self.fullName +",dob="+self.dob+",sortedTimes="+self.sortedTimes+"]")
TypeError: Can't convert 'list' object to str implicitly

我需要在打印方法中打印 Athlete 的实例。

我该如何在Python中做到这一点呢?

2 个回答

1

你的 join 调用不太对。你可能想要的是这样的:

def __str__(self):
    return "Athlete[fullName="
        + str(self.fullName)
        + ",dob="
        + str(self.dob)
        + ",sortedTimes="
        + str(self.sortedTimes)
        + "]"

我在每个属性前面加了 str,因为我不确定你把 list 放在哪个属性里。问题很明显,错误提示说明了:列表不能自动转换成字符串,你需要通过 str() 来明确地进行这种转换。你的某个属性(可能是 dobtimes)是一个列表。

2

times 转换成字符串,然后:

return "Athlete[fullName=" + self.fullName  + ",dob=" + self.dob + ",sortedTimes=" + str(self.sortedTimes) + ']'

这里不需要用 ''.join()

更好的选择是使用字符串格式化:

return "Athlete[fullName={0.fullName},dob={0.dob},sortedTimes={0.sortedTimes}]".format(self)

撰写回答