无法使用列表元素作为新变量的名称来创建新实例

Can't create new instances by using a list element as the name for the new variable

我无法使用列表元素 line[1] 作为实例名称创建 class Pokemon 的新实例。

pokedex = open('../resource/lib/public/pokedex.csv', 'r')
first_line = pokedex.readline() #Skip the header

class Pokemon:
    def __init__(self, number, name, type1, type2, HP, attack, defense, special_atk,special_def, speed, generation, legendary, mega):
        self.number = int(number)
        self.name = str(name)
        self.type1 = type1
        self.type2 = type2
        self.HP = int(HP)
        self.attack = int(attack)
        self.defense = int(defense)
        self.special_atk = int(special_atk)
        self.special_def = int(special_def)
        self.speed = int(speed)
        self.generation = int(generation)
        self.legendary = bool(legendary)
        self.mega = bool(mega)

for line in pokedex:
    line = line.strip().split(",") 
    #line[1] is the name (string) of the Pokemon instance
    line[1] = Pokemon(*line)

print(Kakuna) #NameError: name 'Kakuna' is not defined
print(line[1]) #This gives a correct instance created from the last line of the file

好吧,这个错误是有道理的,因为您从未定义过名称 Kakuna。您正在使用

将新实例分配给 line 的第二个元素
line[1] = Pokemon(*line)

我想那不是你想做的。

有一些方法可以动态地执行此操作,但我强烈建议您不要这样做:How do I create a variable number of variables?

改用dict

pokemons = {}
for line in pokedex:
    line = line.strip().split(",") 
    #line[1] is the name (string) of the Pokemon instance
    pokemons[line[1]] = Pokemon(*line)

然后您可以使用

访问实例
print(pokemons['Kakuna'])