不能通过使用列表元素作为新变量的名称来创建新实例



我无法使用列表元素line[1]作为实例名称来创建类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)

我想这不是你想做的。

有一些方法可以动态地做到这一点,但我敦促你不要这样做:如何创建可变数量的变量?

请改用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'])

相关内容

  • 没有找到相关文章

最新更新