1

I can't create new instances of the class Pokemon using list element line[1] as the name of the instance.

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
finefoot
  • 9,914
  • 7
  • 59
  • 102

1 Answers1

2

Well, the error makes sense since you didn't ever define the name Kakuna. You're assigning the new instance to the second element of line with

line[1] = Pokemon(*line)

That's not what you wanted to do, I guess.

There are ways to do this dynamically, however I urge you not to do so: How do I create a variable number of variables?

Use a dict instead:

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

You can then access the instances with

print(pokemons['Kakuna'])
finefoot
  • 9,914
  • 7
  • 59
  • 102
  • And if you really need to, you can do `globals().update(pokemons)`/`locals().update(pokemons)` afterwards... – Graipher Dec 31 '18 at 15:49