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

为何代码触发AttributeError?ScrollingCredits类无load_credits属性

问题解决:AttributeError: 'ScrollingCredits' object has no attribute 'load_credits'

核心原因

你的load_credits方法缩进错误,被嵌套在了__init__方法内部,导致它不是ScrollingCredits类的成员方法,实例化时自然无法访问这个属性。

修正及优化步骤

  1. 调整方法层级:将load_credits的缩进拉至与__init__同一层级,使其成为类的成员方法。
  2. 修复循环逻辑:原代码中line = string.rstrip(line)和credits.append(line)的缩进错误,会导致仅添加最后一行内容,需将其移入while循环内部。
  3. 优化文件操作:使用with语句自动管理文件资源,避免手动关闭文件可能引发的问题。
  4. 补充必要依赖:确保导入string模块,以及提前定义FONT_SIZE、SCROLL_SPEED等常量。

修正后的完整代码

import pygame
import string

# 提前定义所需常量
FONT_SIZE = 30
SCROLL_SPEED = 2
SCROLL_PAUSE = 1000
END_WAIT = 5000

def load_image(filename, transparent):
    # 补充你的load_image实现逻辑
    pass

class ScrollingCredits:
    def __init__(self):
        self.load_credits("end_credits.txt")
        (self.background, self.background_rect) = load_image("starfield.gif", True)
        self.font = pygame.font.Font(None, FONT_SIZE)
        self.scroll_speed = SCROLL_SPEED
        self.scroll_pause = SCROLL_PAUSE
        self.end_wait = END_WAIT
        self.reset()

    def load_credits(self, filename):
        credits = []
        with open(filename, 'r') as f:
            line = f.readline()
            while line:
                stripped_line = string.rstrip(line)
                credits.append(stripped_line)
                line = f.readline()
        self.lines = credits

    def reset(self):
        # 补充reset方法的实现逻辑
        pass

额外说明

  • with open(...)会在代码块结束后自动关闭文件,比手动调用f.close()更安全。
  • 也可以将while循环替换为更简洁的for line in f遍历方式,效果一致且可读性更强。
  • 需确保reset方法已实现,否则实例化时会触发新的AttributeError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:20:27