data_garden data_garden - 18 days ago 8
Python Question

Python - Create and instantiate class

I am building a

class
of playlists, which will hold many playlists of the same genre.

class playlist(object):
def __init__(self,name):
self.name = name


I would like to instantiate them passing the user:

def hard_rock(self,user):
self.user = user
#query and retrieve data from music API
#return playlist

def pop_rock(self,user):
self.user = user
#query and retrieve data from music API
#return playlist

#and so on


create instance:

r = playlist('rock')
r.hard_rock('user1')


is this a logical way of building and instantiating classes?

Answer

If I understand correctly, you want playlists and users

class Playlist(object):
    def __init__(self, name):
        self.name = name
        self.liked_by = list()

    @classmethod
    def get_genre(cls, genre):
        # this relies on no instance of this class
        pass
        # return api data...

class User(object):
     def __init__(self, name):
         self.name = name

     def likes_playlist(self, playlist):
         playlist.liked_by.append(self.name)

And then, some examples

playlists = list()
hard_rock = Playlist('hard_rock')

joe = User('joe')
joe.likes_playlist(hard_rock)

playlists.append(hard_rock)
playlists.append(Playlist('pop_rock'))

country = Playlist.get_genre('country')
Comments