Python - 自动创建类实例

时间:2017-01-02 01:58:17

标签: python class instantiation

我有几十种以这种方式构建的类:

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将在playlist_type_n通过以下方式选择command line

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

将创建并运行实例:

thom = playlist_type1('Thom Yorke', string)

可以在class scope

中实施

1 个答案:

答案 0 :(得分:1)

创建名称到类的映射,然后基于以下内容实例化类:

class PlaylistType1(Radio):
    pass


class PlaylistType2(Radio):
    pass


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

...

playlist = playlist_types[chosen_type](user)