如果我键入print SongList [i],则在代码底部的循环似乎不会显示歌曲标题,它会打印给定对象的内存地址。我确定它返回的是歌曲列表,但返回的是对象属性。我想念一种方法吗?抱歉,如果过去已经回答过,我找不到示例。
class Song:
def __init__(self, title, artist, duration = 0):
self.title = title
self.artist = artist
self.duration = duration
class Album:
def __init__(self, albumTitle, releaseYear, albumSize):
self.albumTitle = albumTitle
self.releaseYear = releaseYear
self.trackList = []
self.albumSize = albumSize
def addSong(self, albumSong, position):
self.trackList.append((position, albumSong))
class Artist:
def __init__(self, name, year):
self.name = name
self.year = year
self.members = []
def addMembers(self, bandMember):
self.members.append(bandMember)
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
BlinkAndSee = Album("Blink and See", 2018, 5)
Band = Artist("Dinkers", 2002)
AlexThomas = Person("Alex Thomas", 23, "Female")
SeanJohnson = Person("Sean Johnson", 25, "Male")
SineadMcAdams = Person("Sinead McAdams", 21, "Female")
Band.members.append(AlexThomas)
Band.members.append(SeanJohnson)
Band.members.append(SineadMcAdams)
Stoner = Song("Stoner", Band, 320)
Blink = Song("Blink and See", Band, 280)
See = Song("See", Band, 291)
DumbnessAndSand = Song("Dumbness and Sand", Band, 231)
OrangeYellow = Song("Orange Yellow", Band, 353)
BlinkAndSee.trackList.append(Stoner)
BlinkAndSee.trackList.append(BlinkAndSee)
BlinkAndSee.trackList.append(See)
BlinkAndSee.trackList.append(DumbnessAndSand)
BlinkAndSee.trackList.append(OrangeYellow)
SongList = BlinkAndSee.trackList
#Loop through the Song list from album tracklist
for i in range(SongList.__len__()):
print(SongList[i].title)
答案 0 :(得分:0)
这是由(可能是)错字引起的:
请注意您如何附加BlinkAndSee.trackList.append(BlinkAndSee)
?
这实际上是将对象本身附加到跟踪列表中;
当然,这将导致错误,因为“艺术家”不具有在遍历列表时要进一步访问的属性title
。
在这种情况下,我建议您在Album.addSong()
函数中添加一些行,以验证传递的参数is of a certain type;
像
def addSong(self, albumSong, position):
if not isinstance(albumSong, Song):
print("Passed wrong type to addSong")
else:
self.trackList.append((position, albumSong))