Python-创建并实例化类

Python-创建并实例化类

问题描述:

我正在建立播放列表的 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

创建实例:

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

这是构建和实例化类的逻辑方法吗?

is this a logical way of building and instantiating classes?

如果我理解正确,则需要播放列表和用户

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)

然后是一些例子

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