Python class - Set & Delete methods?

2019-09-07 09:23发布

问题:

First I'd like to mention that I am completely new to Python and I've found it a bit difficult to transition from C++. I apologize if my question comes off as elementary.

I have a class for 'songs' which I have initialized as following. It takes in data from a file that contains a song's ID, name, genre etc. all separated by ::.

    def __init__(self):
            self.song_names = dict()
            self.song_genres = dict()

    def load_songs(self,  song_id):
            f = open(song_id)
            for line in f:
                    line = line.rstrip()
                    component = line.split("::")
                    sid = components[0]
                    same= components[1]
                    sgenre=components[2]
            self.song_names[mid] = sname
            self.song_genres[mid] = sgenre
            f.close()

The program also takes in data from a file with 'users' information, separated as UserID::Gender::Age::Occupation::Zip etc. and a file with 'ratings'.

I would I implement a function like def set_song(sid, list((title,genres))) and something like delete_song(sid) ?

I'm going to have to wind up doing a ton more other functions, but if someone could help me with those two - at least to have a better idea of structure and syntax - handling the others should be easier.

回答1:

Why not just inherit from dict and use its interface? That way you can use Python's standard mapping operations instead of rolling your own:

class Songs(dict):

    def load(self, song_id):
        with open(song_id, 'r') as f:
            for line in f:
                sid, name, genre = line.rstrip().split('::')[:3]
                self[sid] = [name, genre]

mysongs = Songs()
mysongs.load('barnes_and_barnes__fish_heads')
mysongs['barnes_and_barnes__fish_heads'] = ['roly poly', 'strange']  # set
del mysongs['barnes_and_barnes__fish_heads']                         # delete


标签: python class