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

Python实现Team类调用get_win_percentage报AttributeError如何解决

错误原因
  • 核心问题是get_win_percentage方法的缩进错误:你把它写在了__init__构造方法的内部,它就变成了__init__的局部函数,不属于Team类的实例方法,外部实例调用时自然找不到对应方法,触发AttributeError。
  • 额外还存在多处缩进错误:类定义下的__init__方法、if __name__ == "__main__"代码块下的逻辑都没有正确缩进,Python对缩进敏感,这些错误也会导致运行异常。
修复方案

调整方法缩进层级,把get_win_percentage放到和__init__同级的类成员位置,同时修正所有缩进问题,修复后的完整代码如下:

class Team:
    def __init__(self):
        self.team_name = 'none'
        self.team_wins = 0
        self.team_losses = 0
    
    # 调整缩进,和__init__同级,成为类实例方法
    def get_win_percentage(self):
        # Python3中/默认就是浮点除法,符合要求
        return self.team_wins / (self.team_wins + self.team_losses)


if __name__ == "__main__":
    team = Team()

    team_name = input()
    team_wins = int(input())
    team_losses = int(input())

    team.team_name = team_name
    team.team_wins = team_wins
    team.team_losses = team_losses

    if team.get_win_percentage() >= 0.5:
        print('Congratulations, Team', team.team_name,'has a winning average!')
    else:
        print('Team', team.team_name, 'has a losing average.')
效果验证

输入Ravens、13、3时,胜率计算为13/(13+3)=0.8125≥0.5,输出Congratulations, Team Ravens has a winning average!
输入Angels、80、82时,胜率计算为80/(80+82)≈0.4938<0.5,输出Team Angels has a losing average.,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:09:03