Python自动创建类实例

2024-04-20 14:49:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多这样的课程:

class playlist_type_1(radio):
    '''child class'''   
    def __init__(self,user, type):
        radio.__init__(self, user, type)


class playlist_type_2(radio):
    '''child class'''       
        def __init__(self,user,type):
            radio.__init__(self, user, type)

它们继承自:

class radio(self, user, type):
   '''parent class'''

因为我将有许多users,所以我尝试构建一个模型来创建这样的实例:

thom = playlist_type1('Thom Yorke', 'playlist_type_1')

用户本人thom将通过以下方式选择位于command lineplaylist_type_n

string = raw_input('Choose a playlist type> ')

实例将被创建并运行:

thom = playlist_type1('Thom Yorke', string)

这能在class scope内实现吗?你知道吗


Tags: 实例selfchildstringinitdeftypeplaylist
1条回答
网友
1楼 · 发布于 2024-04-20 14:49:48

创建名称到类的映射,然后基于该映射实例化类:

class PlaylistType1(Radio):
    pass


class PlaylistType2(Radio):
    pass


playlist_types = {
    PlaylistType1.__name__: PlaylistType1,
    PlaylistType2.__name__: PlaylistType2,
}

...

playlist = playlist_types[chosen_type](user)

相关问题 更多 >