如何将Pokemon对象的字符串类型evolution属性替换为对应实例
问题解决:批量将Pokemon的evolution字符串属性替换为对象实例
核心错误梳理
你之前的代码主要存在三个问题:
- 遍历
pokemon_db时默认取的是字典的键(字符串编号),而非Pokemon对象,导致触发'str' object has no attribute 'evolution'错误 - 条件判断逻辑混乱,比如
Pokemon.evolution in pokemon_db is type(str)这种写法完全不符合Python语法规范 - 大小写/拼写错误,比如
Pokemon_db应为pokemon_db
正确实现代码
先构建一个名称到对象的映射字典(因为你的evolution字符串是小写对象名,比如"ivysaur"),再批量遍历更新:
# 先创建小写名称到Pokemon对象的映射,方便快速查找 name_to_pokemon = {poke.name.lower(): poke for poke in pokemon_db.values()} # 遍历所有Pokemon对象 for pokemon in pokemon_db.values(): # 检查evolution是否为有效字符串 if isinstance(pokemon.evolution, str) and pokemon.evolution: # 从映射中获取对应对象 target_pokemon = name_to_pokemon.get(pokemon.evolution) if target_pokemon: pokemon.evolution = target_pokemon else: print(f"未找到名为{pokemon.evolution}的宝可梦,跳过更新")
验证效果
运行后执行以下代码,结果和你手动更新的一致:
print(ivysaur.evolution.name) # 输出: Venusaur print(ivysaur.evolution.pokedex_number) # 输出: 0003 print(f"Ivysaur's evolution is {ivysaur.evolution.name}, and it originally evolves from {ivysaur.pre_evolution.name}.") # 输出: Ivysaur's evolution is Venusaur, and it originally evolves from Bulbasaur.
额外优化:同步处理pre_evolution字符串
如果你的pre_evolution也存在字符串形式(比如charizard的pre_evolution是"charmeleon"),可以用同样逻辑批量处理:
for pokemon in pokemon_db.values(): # 更新evolution if isinstance(pokemon.evolution, str) and pokemon.evolution: target = name_to_pokemon.get(pokemon.evolution) if target: pokemon.evolution = target # 更新pre_evolution if isinstance(pokemon.pre_evolution, str) and pokemon.pre_evolution: target = name_to_pokemon.get(pokemon.pre_evolution) if target: pokemon.pre_evolution = target
内容的提问来源于stack exchange,提问作者mycode.exe
相关产品推荐
相关产品推荐

