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

使用Python turtle开发太空战游戏时遇self参数缺失报错求助

解决Python turtle太空战游戏中TypeError的问题

错误原因

你直接通过类game2调用了实例方法show_lives(),但实例方法必须绑定到类的实例上才能正常运行——self参数会自动传入实例对象,直接用类调用时没有这个对象传入,因此触发missing 1 required positional argument: 'self'报错。另外你的代码还有两处隐性问题:self.pen未初始化、格式化字符串的格式符错误。

修复方案

  1. 先创建类实例再调用方法:实例化game2类,通过实例对象调用show_lives()
  2. 初始化画笔对象:在__init__方法中创建turtle.Turtle实例赋值给self.pen
  3. 修正格式化符:把无效的%l改为适合整数的%d
  4. 处理首次撤销异常:第一次调用show_lives()时没有可撤销的内容,需要捕获TurtleGraphicsError避免报错

修改后的完整代码

import turtle

class game2():
    def __init__(self):
        self.lives = 3
        # 初始化画笔并设置基础属性
        self.pen = turtle.Turtle()
        self.pen.hideturtle()
        self.pen.speed(0)

    def show_lives(self):
        # 捕获首次调用时的撤销异常
        try:
            self.pen.undo()
        except turtle.TurtleGraphicsError:
            pass
        # 用%d格式化整数生命值
        msg2 = "Lives: %d" % self.lives
        self.pen.penup()
        self.pen.goto(-200, 310)
        self.pen.write(msg2, font=("Arial", 16, "normal"))

# 创建游戏类实例
game = game2()
# 通过实例调用生命值显示方法
game.show_lives()

# 保持turtle窗口持续显示
turtle.done()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:03:15