gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:19:26 25 4
gpt4 key购买 nike

我无法使用列表元素 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)

我猜这不是你想做的。

有多种方法可以动态地执行此操作,但我强烈建议您不要这样做: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'])

关于python - 无法使用列表元素作为新变量的名称来创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com