我正在制作class
个播放列表,其中包含许多相同类型的播放列表。
class playlist(object):
def __init__(self,name):
self.name = name
我想实例化它们传递用户:
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')
这是构建和实例化类的逻辑方式吗?
答案 0 :(得分:2)
如果我理解正确,您需要播放列表和用户
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')
答案 1 :(得分:1)
如果播放列表是应用程序的核心组件(使用类继承的非常简单的示例),那么这样的事情是可能的。
>>> class playlist:
... def __init__(self,name, user):
... self.name = name
... self.user = user
...
>>> class hardrock(playlist):
... def __init__(self,name, user):
... playlist.__init__(self, name, user)
...
>>> test = hardrock('my_awesome_hardrock_list', 'my_awesome_username')
>>> print test.name
my_awesome_hardrock_list
>>> print test.user
my_awesome_username
您可以开始仅为用户使用字符串,然后将其替换为真实对象,并在播放列表和用户之间添加某种关系。请参阅cricket_007关于更多想法的建议。