-2

I would like to ask a question about the below's code. If I create an instance of Album, say variable myalbum, after defining an artist, and also run add_track in order to add a song to the album, how can I access myalbum.tracks in a readable form, i.e. in a list form? Right now, I get <main.Song at 0x4a9ef90> object notation only.

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)
        #
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)

Thanks in advance! Igor

igordr
  • 1
  • 2
  • 1
    Possible duplicate of [How do I change the string representation of a Python class?](https://stackoverflow.com/questions/4912852/how-do-i-change-the-string-representation-of-a-python-class) – Tomer Shemesh Jan 29 '18 at 13:46
  • I dont see where you are printing in your code? But likely you need to go into the object to select the var. So right now you are doing this: `print object` but need `print object.artist` – Zack Tarr Jan 29 '18 at 13:48
  • You should get list of instance of Song class – AlokThakur Jan 29 '18 at 13:54

1 Answers1

0

What happens when you perform myalbum.add_track is you're appending a Song instance to myalbum.tracks, so when you print your list, it returns the Song instance rather than the title of the song.

What you could do is create an empty list and use a for loop to append the titles of each Song instance in your myalbum list to it, and then printing that list:

myalbum_song_titles = []
for track in myalbum.tracks:
    myalbum_song_titles.append(track.title)
print(myalbum_song_titles)
Jason Ngo
  • 191
  • 1
  • 5