首页 > 解决方案 > 如何制作对象的列表元素实例

问题描述

我正在尝试遍历字符串列表并使每个元素成为对象的实例。我制作了一个简化版本只是为了演示我的问题。当我运行此代码时,我收到一条错误消息,指出未定义“David”。我明白我做错了什么:当我写 'People[i] = Person()' 时,People[i] 变成了变量名,而不是调用列表中的每个元素。

如何调用列表中的每个元素并使其成为变量,以便在这种情况下,当我打印(David.name)时,它会打印“大卫”?

class Person:
    def __init__(self):
        self.name = "Unassigned"



People = ["David", "Emma", "Brian"]

for i in range(len(People)):
    People[i] = Person()
 
print(David.name)

标签: pythonlistclassvariableselement

解决方案


不要分配这样的变量名或弄乱全局变量。改用字典:

class Person:
    def __init__(self):
        self.name = 'Unassigned'

People = ["David", "Emma", "Brian"]

#create a list of your objects
obj_list = [Person() for i in range(len(People))]
#convert People names to dictionary keys
dictionary = dict(zip(People, obj_list))

print(dictionary['David'].name)
#Unassigned

推荐阅读