Reputation: 3432
I have python class:
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__()
Instances of this class are stored in map athleteMap
as values.
When I do print(athleteMap)
I get this error:
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
I need to print Athlete
instance in print method.
How to do this in python?
Upvotes: 0
Views: 3587
Reputation: 35891
Your join
call doesn't make sense. You probably want something like this:
def __str__(self):
return "Athlete[fullName="
+ str(self.fullName)
+ ",dob="
+ str(self.dob)
+ ",sortedTimes="
+ str(self.sortedTimes)
+ "]"
I've added str
to every attribute because I can't know for sure in which one of them you put a list
. The problem is evident from the error - lists can't be converted implicitly to string - you need to mark this conversion explicitly via str()
call. One of your attributes (dob
or times
most probably) is a list.
Upvotes: 1
Reputation: 1122252
Convert times
to a string explicitly then:
return "Athlete[fullName=" + self.fullName + ",dob=" + self.dob + ",sortedTimes=" + str(self.sortedTimes) + ']'
You don't need ''.join()
here.
A better option is to use string formatting:
return "Athlete[fullName={0.fullName},dob={0.dob},sortedTimes={0.sortedTimes}]".format(self)
Upvotes: 2