如果我有一个类和一个名字列表,我被要求将列表中的每个名称实例化为该类的对象,我该怎么做?
class PlaceHolder():
'''This class represents a place holder for this example'''
pass
listofnames = ['Michael', 'Jay', 'Derrick']
for next_name in listofnames:
next_name = PlaceHolder()
这不起作用。我想知道是否有方法来实现这个?
答案 0 :(得分:0)
它不起作用的原因是你试图将类初始化为列表项,这不会做任何事情。 for
循环for next_name in listofnames
会遍历listofnames
中的值。
尝试,
listofnames = ['Michael', 'Jay', 'Derrick']
list_dict = dict()
for next_name in listofnames:
list_dict[next_name] = PlaceHolder()
每个列表项都有一个已分配的占位符,并放在字典list_dict
中。可以通过list_dict[next_name]
答案 1 :(得分:0)
您确实正在创建对象。问题是你总是将它存储在同一个变量中,所以你要覆盖它。也许你看起来像这样
class PlaceHolder():
'''This class represents a place holder for this example'''
pass
listofnames = ['Michael', 'Jay', 'Derrick']
instances = list()
for next_name in listofnames:
instances.append(PlaceHolder())
print(instances)
或者更加pythonic的方式
instances = [PlaceHolder() for next_name in listofnames]
print(instances)
答案 2 :(得分:0)
如果您绝对需要按照建议的方式设置变量,可以使用以下内容:
for next_name in listofnames:
exec("{} = Placeholder()".format(next_name))
由于使用exec
的危险,我真的不建议这样做。真的,不要这样做。
将它们作为字典中的键保持好得多。
my_objects = {}
for next_name in listofnames:
my_objects[next_name] = Placeholder()
# And access via
my_objects['Michael'] # Placeholder instance
答案 3 :(得分:0)
你可以试试这个:
class PlaceHolder():
'''This class represents a place holder for this example'''
pass
listofnames = ['Michael', 'Jay', 'Derrick']
for next_name in listofnames:
globals()[next_name] = PlaceHolder() #create an instance of class PlaceHolder with name=next_name
listofnames[listofnames.index(next_name)]=globals()[next_name] #replace the string in list with the class instance