Python class - Set & Delete methods?

浪尽此生 提交于 2019-12-25 03:06:25

问题


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


来源:https://stackoverflow.com/questions/21818037/python-class-set-delete-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!