[Python] How to update string attributes to object instances if they exist

Discussão em 'Python' iniciado por Stack, Agosto 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to use a for loop to iterate through a set of variables, check if those variables stored string data (specifically their 'Pokemon.evolution' string) is the same as a variable name in the set, and then replace that string with the variable name itself.

    I've tried various ways of writing the for loop, but nothing seems to do what I want it to. Here it is in "plain speak" to hopefully explain what I mean:

    for x in ():
    if Pokemon.name is in pokemon_db:
    pokemon_db = Pokemon.evolution
    else:
    pass


    Here is the code I have so far:

    class Pokemon:
    def __init__(self, name, pokedex_number, height, weight, category, abilities, type, weaknesses, pre_evolution, evolution, image):
    self.name = name
    self.pokedex_number = pokedex_number
    self.height = height # in Metres (Format: float)
    self.weight = weight # in Kilograms (Format: float)
    self.category = category
    self.abilities = abilities
    self.type = type
    self.weaknesses = weaknesses
    self.pre_evolution = pre_evolution # If n/a - Mark as ' False '
    self.evolution = evolution # If n/a - Mark as ' False '
    self.image = image # Pokedex image stored in 'pokedex_images' folder
    ...

    bulbasaur = Pokemon("Bulbasaur", "0001", 0.7, 6.9, "Seed", "Overgrow", "Grass"+"Poison", "Fire"+"Ice"+"Flying"+"Psychic", None, "Ivysaur", ...)
    ivysaur = Pokemon("Ivysaur", "0002", 1.0, 13.0, "Seed", "Overgrow", "Grass"+"Poison", "Fire"+"Ice"+"Flying"+"Psychic", bulbasaur, "venusaur", ...)
    venusaur = Pokemon("Venusaur", "0003", 2.0, 100.0, "Seed", "Overgrow", "Grass"+"Poison", "Fire"+"Ice"+"Flying"+"Psychic", ivysaur, None, ...)

    pokemon_db = {bulbasaur, ivysaur, venusaur}


    I've managed to do the change manually, using this code, but I want to know if the program can do the check & update for me.

    # Evolution updates to attributes
    ivysaur.evolution = venusaur
    charmeleon.evolution = charizard
    wartortle.evolution = blastoise

    Continue reading...

Compartilhe esta Página