Python-创建并实例化类 [英] Python - Create and instantiate class

查看:56
本文介绍了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')

这篇关于Python-创建并实例化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆