简体   繁体   English

如何在循环中为每个类实例输出__str__

[英]How to print out __str__ for each instance of a class in a loop

I have a playlist of songs, and I would like to create an instance of the class SongData for each song in the playlist. 我有一个歌曲的播放列表,我想为该播放列表中的每首歌曲创建一个类SongData的实例。 I have code that isn't included that extracts the song name, artist, and song directory from the playlist. 我有未包含的代码,用于从播放列表中提取歌曲名称,艺术家和歌曲目录。 For the purposes of this question I have included these as 3 lists, songNames, artistNames, dirNames. 出于这个问题的目的,我将这些作为3个列表包括在内,即songNames,artistNames和dirNames。

class SongData(object):
    def __init__(self, title="", artist="", directory=""):
        self.title, self.artist, self.directory = title, artist, directory
    def __str__(self):
        desc_str = "Title: %s \nArtist: %s \nDirectory: %s \n" %(self.title,
                                            self.artist, self.directory)
        print desc_str

songNames = ['song1', 'song2', 'song3']
artistNames = ['artist1', 'artist2', 'artist3']
dirNames = ['dir1', 'dir2', 'dir3']

songs = {name: SongData(title=name) for name in songNames}
artists = {band: SongData(artist=band) for band in artistNames}
directorys = {direc: SongData(directory=direc) for direc in dirNames}

I would like to be able to print out the desc_str for each song so it appears like this: 我希望能够为每首歌曲打印出desc_str,因此它看起来像这样:

Title: song1 
Artist: artist1 
Directory: dir1

But so far I have only managed to call one data category at once, so it prints Title: song1 but leaves the Artist: and Directory: sections blank. 但是到目前为止,我只设法一次调用了一个数据类别,因此它打印了Title:song1,但将Artist:Directory:部分留为空白。 I have been using: 我一直在使用:

print songs['song1']
print artists['artist1']

How can I get it to print them out all at once? 我怎样才能一次将它们全部打印出来? I think the problem is that I am only referencing the data in each dictionary, not calling the instance of the class relevant to that song. 我认为问题在于我只引用每个词典中的数据,而没有调用与该歌曲相关的类的实例。

When I do it simply and manually, as follows, it works, but I cannot figure out how to put this into a loop so it will work for the lists songNames , artistNames , dirNames . 当我按如下所述简单而手动地进行操作时,它可以工作,但是我无法弄清楚如何将其放入循环中,因此它可以用于列表songNamesartistNamesdirNames

p = SongData('song1', 'artist1', 'dir1')
p.__str__()

Your SongData class needs to return from the __str__ function: 您的SongData类需要从__str__函数return

class SongData(object):
    def __init__(self, title="", artist="", directory=""):
        self.title, self.artist, self.directory = title, artist, directory
    def __str__(self):
        desc_str = "Title: %s \nArtist: %s \nDirectory: %s \n" %(self.title,
                                            self.artist, self.directory)
        return desc_str # <------ RETURN HERE

Then, you can build up instances of SongData as such: 然后,您可以像这样构建SongData实例:

songNames = ['song1', 'song2', 'song3']
artistNames = ['artist1', 'artist2', 'artist3']
dirNames = ['dir1', 'dir2', 'dir3']

songdata = [SongData(*params) for params in zip(songNames, artistNames, dirNames)]

Note that the above is a list-comp that given the above 3 lists is effectively equivalent to: 请注意,以上是一个list-comp,上面给出的3个列表实际上等效于:

songdata = [
    SongData('song1', 'artist1', 'dir1'),
    SongData('song2', 'artist2', 'dir2'),
    SongData('song3', 'artist3', 'dir3')
]

Then loop over those, and use print to get the result of your __str__ : 然后遍历这些,并使用print获得__str__的结果:

for song in songdata:
    print song

Gives you: 给你:

Title: song1 
Artist: artist1 
Directory: dir1 

Title: song2 
Artist: artist2 
Directory: dir2 

Title: song3 
Artist: artist3 
Directory: dir3 

Or it is also possible to print a for loop within the __str__ function and then return empty string. 或者也可以在__str__函数中打印一个for循环,然后返回空字符串。

def __str__(self):
    for item in self.UserClasses:
        print item
    return ""

This works like a charm for me. 这对我来说就像是一种魅力。 Although might not be the best practice. 虽然可能不是最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM