TypeError:无法将“list”对象隐式转换为str

2024-04-29 10:21:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有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__()

此类的实例作为值存储在map athleteMap中。在

当我print(athleteMap)时,我得到了这个错误:

^{pr2}$

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

如何在python中实现这一点?在


Tags: 实例selfreturninitisdefclassprint
2条回答

你的join调用没有意义。你可能想要这样的东西:

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

我已经将str添加到每个属性中,因为我无法确定您在其中的哪个属性中添加了list。这个问题从错误列表中很明显-不能隐式转换为字符串-您需要通过str()调用显式地标记此转换。您的一个属性(dobtimes很可能)是一个列表。在

times显式转换为字符串,然后:

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

这里不需要''.join()。在

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

^{pr2}$

相关问题 更多 >