我这里有两节课。在我的课堂相册中,我的 str 功能无效,因为我只能返回其中一个专辑详情。 测试:
t1 = Track('Bicyclops', 'Bela Fleck', 260)
t3 = Track('Watch What Happens', 'Frank Sinatra', 200)
album1 = Album('My Way', 'Frank Sinatra', '1969', [t1, t3])
print(album1)
它返回的内容My Way by Frank Sinatra (1969)
但我希望它能够回归
My Way by Frank Sinatra (1969)
Track: Bicyclops by Bela Fleck (260)
Track: Watch What Happens by Frank Sinatra (200)
我知道我需要创建一个单独的函数并在 str 中调用它,但我不知道如何处理它。我已经创建了额外的功能track_list但不是100%肯定。这是一个很长的问题,但这是我能用最好的方式解释它的唯一方法。
class Track:
def __init__(self, title, artist,duration):
self.artist = artist
self.title = title
self.duration = duration
def __repr__(self):
return 'Track(' + str(self.artist) + ", " + str(self.title) + ", " + str(self.duration) + ')'
def __str__(self):
return "Track: " + str(self.title) + " by " + str(self.artist) + " (" + str(self.duration) + ")"
def get_artist(self):
return self.artist
def get_title(self):
return self.title
def get_duration(self):
return self.duration
class Album:
def __init__(self, title, artist, year, list_of_tracks):
self.artist = artist
self.title = title
self.year = year
self.list_of_tracks = list_of_tracks
def __repr__(self):
return 'Album(' + str(self.artist) + ", " + str(self.title) + ", " + str(self.year) + ')'
def track_list(self,artist,title,duration):
track1 = "Track: " + str(self.title) + " by " + str(self.artist) + " (" + str(self.duration) + ")"
track2 = "Track: " + str(self.title) + " by " + str(self.artist) + " (" + str(self.duration) + ")"
return track1, track2
def __str__(self):
return str(self.title) + " by " + str(self.artist) + " (" + str(self.year) + ")"
答案 0 :(得分:2)
试试这个,
class Album:
..............
def __str__(self):
return str(self.title) + " by " + str(self.artist) + " (" + str(self.year) + ")"+str(self.list_of_tracks)
如果你想要分开的话,
方法1:
class Album:
..............
def __str__(self):
tempStr=''
for item in self.list_of_tracks:
tempStr += '\n'+str(item);
return str(self.title) + " by " + str(self.artist) + " (" + str(self.year) + ")"+tempStr