You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:从CSV读取属性实例化类并打印指定属性

修正后的代码及问题解析

原代码存在的核心问题

  • 列索引与属性对应错误:你的CSV行顺序为name, type1, type2, Health, Atk, Def, SpAtk, SpDef, Spd,但实例化时错误地将row[3](对应CSV的Health值)传给了Atk参数,导致所有属性值错位。
  • 实例方法调用错误:pokeprint是Pokemon类的实例方法,必须通过类的实例对象调用,不能直接当作普通函数使用。
  • 未正确获取目标实例:Bulbasaur是字符串,不是定义好的变量,需要从存储的实例集合中查找对应的对象。

方案1:通用属性打印版本(推荐)

这个版本使用字典存储实例便于查找,同时提供可指定属性的打印方法,灵活性更高:

import csv

class Pokemon:
    def __init__(self, name, type1, type2, health, atk, defense, sp_atk, sp_def, spd):
        # 遵循PEP8命名规范,使用小写属性名
        self.name = name
        self.type1 = type1
        self.type2 = type2
        self.health = health
        self.atk = atk
        self.defense = defense
        self.sp_atk = sp_atk
        self.sp_def = sp_def
        self.spd = spd

    def print_attribute(self, attr_name):
        """打印指定属性,若属性不存在则提示"""
        if hasattr(self, attr_name):
            print(f"{self.name}的{attr_name}:{getattr(self, attr_name)}")
        else:
            print(f"错误:不存在属性 {attr_name}")

# 用字典存储实例,通过宝可梦名字快速查找
pokemon_map = {}

with open('Pokemon.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    # 你的CSV无表头,无需跳过行
    for row in reader:
        # 严格对应CSV列顺序赋值
        pokemon = Pokemon(
            name=row[0],
            type1=row[1],
            type2=row[2],
            health=int(row[3]),
            atk=int(row[4]),
            defense=int(row[5]),
            sp_atk=int(row[6]),
            sp_def=int(row[7]),
            spd=int(row[8])
        )
        pokemon_map[pokemon.name] = pokemon

# 查找并打印Bulbasaur的指定属性
if "Bulbasaur" in pokemon_map:
    bulbasaur = pokemon_map["Bulbasaur"]
    bulbasaur.print_attribute("atk")       # 打印攻击值
    bulbasaur.print_attribute("health")    # 打印生命值
else:
    print("未找到宝可梦:Bulbasaur")

方案2:保留原pokeprint方法的版本

如果你想保留原有打印攻击值的方法,可使用以下代码:

import csv

class Pokemon:
    def __init__(self, name, type1, type2, Health, Atk, Def, SpAtk, SpDef, Spd):
        # 调整参数顺序,匹配CSV列顺序
        self.name = name
        self.type1 = type1
        self.type2 = type2
        self.Health = Health
        self.Atk = Atk
        self.Def = Def
        self.SpAtk = SpAtk
        self.SpDef = SpDef
        self.Spd = Spd

    def pokeprint(self):
        print(f"{self.name}的攻击值:{self.Atk}")

Pokemon_list = []

with open('Pokemon.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        # 对应CSV列顺序实例化
        Pokemon_list.append(Pokemon(
            row[0], row[1], row[2],
            int(row[3]), int(row[4]), int(row[5]),
            int(row[6]), int(row[7]), int(row[8])
        ))

# 遍历列表找到Bulbasaur并调用打印方法
for pokemon in Pokemon_list:
    if pokemon.name == "Bulbasaur":
        pokemon.pokeprint()
        break
else:
    print("未找到宝可梦:Bulbasaur")

内容的提问来源于stack exchange,提问作者James Chin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:23:20