如何在类创建的字典中为实例赋值单个变量并解决属性错误?
问题解决:为每个比赛类实例设置单个x属性值
问题说明
需要将计算得到的单个x值存入字典中每个比赛对应的Info_Matchs类实例,每个比赛对应唯一x值(而非列表)。原代码尝试用test[row[0]].x.append(x)实现时触发AttributeError: 'NoneType' object has no attribute 'append',且当前输出缺少x属性值。
错误原因
- 类型不匹配:
Info_Matchs类中x定义为float类型,不是列表,无法调用append()方法,直接赋值即可。 - 循环变量错误:第二个循环中误用了外层循环的
row[0],此时row指向的是上一个循环的最后一条数据,应使用当前循环的key或直接操作类实例value。 - 类参数不匹配:类定义中参数为
round,但实例化时传入了current_round,导致参数名不匹配,需统一两者名称。
修正后的代码
from dataclasses import dataclass test = {} @dataclass class Info_Matchs: championship: str date: float current_round: int # 修正参数名,与实例化时一致 clock: str score_home: list[int] score_away: list[int] x: float # 数据库查询逻辑保持不变 db = cursor_test.execute('''SELECT Next.team_home||"-"||Next.team_away, Next.tournmant, Next.date, Next.round, Next.time, Results.score_home FROM Next INNER JOIN Results ON Next.team_home = Results.team_home;''') for row in db.fetchall(): if row[0] not in test: info = Info_Matchs( championship=row[1], date=row[2], current_round=row[3], clock=row[4], score_home=list(), score_away=list(), x=None) test[row[0]] = info test[row[0]].score_home.append(row[5]) # 修正x值计算逻辑 for key, value in test.items(): # 计算平均值得到示例中的1.75(sum([0,1,1,5])=7,7/4=1.75) calc = sum(value.score_home) / len(value.score_home) if value.score_home else 0.0 value.x = calc # 直接赋值给x属性,而非调用append # 输出验证结果 for key, item in test.items(): print(f"'{key}': {item}")
验证结果
运行修正后的代码,输出将符合期望格式:
'Minnesota-Vegas': Info_Matchs(championship='NHL', date=8.1, current_round=9, clock='15:00', score_home=[0, 1, 1, 5], score_away=[], x=1.75)
内容的提问来源于stack exchange,提问作者user20812299
相关产品推荐
相关产品推荐

