【问题标题】:Python get object attributesPython获取对象属性
【发布时间】:2018-07-09 07:44:44
【问题描述】:

如果我键入 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)

【问题讨论】:

  • 为什么你的Album 对象中有一个addSong 方法,然后手动使用.tracklist.append(...) 将歌曲添加到曲目列表中?
  • 我无法重现您的问题。它为我打印 Stoner 然后崩溃,因为您将专辑本身添加到其列表中。
  • 如果我将BlinkAndSee.trackList.append(BlinkAndSee) 更改为BlinkAndSee.trackList.append(Blink),它会按照您的描述打印歌名。
  • 总是错字!感谢您的帮助

标签: python-3.x object


【解决方案1】:

这是由(可能)一个错字引起的: 注意你如何附加BlinkAndSee.trackList.append(BlinkAndSee)
这实际上将对象本身附加到轨道列表中; 当然,这会导致错误,因为 Artist 没有属性 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))

【讨论】:

  • 感谢您的帮助,这很有效,我明白您为什么还要检查类型!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多