Python打印对象地址而不是值

时间:2018-07-30 16:16:29

标签: python oop inheritance init

我要打印已添加到tracks[]列表中的所有曲目。当我尝试这样做时,我得到的是该对象位于内存中的地址,而不是其实际值。我显然不明白如何创建对象或将对象从一个类传递到另一类。

class Song:

    def __init__(self, title, artist, album, track_number):
        self.title = title
        self.artist = artist
        self.album = album
        self.track_number = track_number

        artist.add_song(self)


class Album:

    def __init__(self, title, artist, year):
        self.title = title
        self.artist = artist
        self.year = year

        self.tracks = []

        artist.add_album(self)

    def add_track(self, title, artist=None):
        if artist is None:
            artist = self.artist

        track_number = len(self.tracks)

        song = Song(title, artist, self, track_number)

        self.tracks.append(song)
        print(self.tracks)


class Artist:
    def __init__(self, name):
        self.name = name

        self.albums = []
        self.songs = []

    def add_album(self, album):
        self.albums.append(album)

    def add_song(self, song):
        self.songs.append(song)


class Playlist:
    def __init__(self, name):
        self.name = name
        self.songs = []

    def add_song(self, song):
        self.songs.append(song)

band = Artist("Bob's Awesome Band")
album = Album("Bob's First Single", band, 2013)
album.add_track("A Ballad about Cheese")
album.add_track("A Ballad about Cheese (dance remix)")
album.add_track("A Third Song to Use Up the Rest of the Space")
playlist = Playlist("My Favourite Songs")


for song in album.tracks:
    playlist.add_song(song)

2 个答案:

答案 0 :(得分:0)

看起来您正在尝试打印数组,而不是数组中的值。 print(self.tracks)正在打印self.tracks对象,该对象是一个数组。尝试使用print(self.tracks [x]),x是您要打印的字符串的索引。

如果要打印该数组中的所有对象,请遍历它并打印每个对象。

使用它来遍历数组:

for x in range(len(self.tracks)):
    print self.tracks[x].title

for track in self.tracks
    print track.title

要获取每个歌曲对象的标题值,请使用track.title在循环中对其进行寻址。要获取艺术家或年份,请将其更改为track.artist或track.year。

您可以使用相同的逻辑来构建较大的字符串,例如: print(“标题” + track.title +“,艺术家” + track.artist)

答案 1 :(得分:0)

是的,对象的“值”包括其类型和存储位置。您需要提取所需的属性值。请注意,您需要对Song属性中包含的其他对象执行此操作。

执行此操作的一种方法是在类__repr__中实现“表示”方法。对于您的应用程序,它可能看起来像这样:

def __repr__(self):
    return "\n".join([self.title, self.artist.name, self.album.title,
                      "Track " + str(self.track_number)])

现在,每当您在语法上需要使用Song对象的字符串表示形式时,Python都会使用此方法进行转换。无需任何其他编码,您的程序现在将产生:

[A Ballad about Cheese
Bob's Awesome Band
Bob's First Single
Track 0]
[A Ballad about Cheese
Bob's Awesome Band
Bob's First Single
Track 0, A Ballad about Cheese (dance remix)
Bob's Awesome Band
Bob's First Single
Track 1]
[A Ballad about Cheese
Bob's Awesome Band
Bob's First Single
Track 0, A Ballad about Cheese (dance remix)
Bob's Awesome Band
Bob's First Single
Track 1, A Third Song to Use Up the Rest of the Space
Bob's Awesome Band
Bob's First Single
Track 2]

当然,您需要根据自己的列表需求对其进行自定义。