Python - 自动创建 class 个实例
Python - automating the creation of class instances
我有几十个 类 以这种方式构建:
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 line
通过以下方式选择他的 playlist_type_n
:
string = raw_input('Choose a playlist type> ')
将创建实例并且 运行:
thom = playlist_type1('Thom Yorke', string)
这可以在 class scope
内实施吗?
创建名称到 classes 的映射,然后基于此实例化 class:
class PlaylistType1(Radio):
pass
class PlaylistType2(Radio):
pass
playlist_types = {
PlaylistType1.__name__: PlaylistType1,
PlaylistType2.__name__: PlaylistType2,
}
...
playlist = playlist_types[chosen_type](user)
我有几十个 类 以这种方式构建:
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 line
通过以下方式选择他的 playlist_type_n
:
string = raw_input('Choose a playlist type> ')
将创建实例并且 运行:
thom = playlist_type1('Thom Yorke', string)
这可以在 class scope
内实施吗?
创建名称到 classes 的映射,然后基于此实例化 class:
class PlaylistType1(Radio):
pass
class PlaylistType2(Radio):
pass
playlist_types = {
PlaylistType1.__name__: PlaylistType1,
PlaylistType2.__name__: PlaylistType2,
}
...
playlist = playlist_types[chosen_type](user)