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

将Pygame模块test.py重构为类时出现TypeError:缺少self参数求助

问题解决:TypeError: test.run_game() missing 1 required positional argument: 'self'

错误原因及修复步骤

  • 实例化类的方式错误:你当前代码中cl = test只是将类本身赋值给变量,并没有创建类的实例。类的实例方法(如run_game)需要绑定到具体实例上才能自动传入self参数,正确的实例化方式是添加括号调用构造函数:cl = test()。
  • 缺少define_screen方法:代码中调用了self.define_screen()但未定义该方法,运行时会触发新的错误,需要补充实现这个方法(比如用于填充屏幕背景色)。
  • 遗漏Pygame初始化:原代码没调用pygame.init(),这是初始化Pygame模块的必要步骤,否则窗口可能无法正常创建。

修复后的完整代码

import pygame
import sys

class test:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((500, 500))
        pygame.display.set_caption("Pygame Window")

    def define_screen(self):
        # 填充白色背景并更新屏幕
        self.screen.fill((255, 255, 255))
        pygame.display.flip()

    def run_game(self):
        while True:
            self.define_screen()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

if __name__ == '__main__':
    cl = test()
    cl.run_game()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:27:05