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

Pygame类与self使用问题:调用draw方法报错如何解决?

Pygame代码错误分析与修正

你的代码存在两个核心问题,引发了报错:

错误代码

import pygame

pygame.init()

wn = pygame.display.set_mode((200,200))

x = 100
y = 100

class circle():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def draw(self, x, y):
        pygame.draw.circle(wn, (255, 0, 0), (self.x, self.y), 5)

circle.draw(x, y)

错误信息

Traceback (most recent call last):
  File "c:\Users\davey\OneDrive\Documents\Python\Game\main.py", line 17, in <module>
    circle.draw(x, y)
TypeError: circle.draw() missing 1 required positional argument: 'y'

问题分析

  1. 错误调用类方法:draw是类的实例方法,必须先创建类的实例,再通过实例调用方法。直接用circle.draw(x,y)时,Python会把第一个参数x当作实例方法要求的self参数,剩下的y只满足一个参数,自然会提示缺少y参数。
  2. 冗余参数定义:draw方法里使用的是self.x和self.y(实例初始化时保存的坐标),完全不需要额外传入x和y作为方法参数,这部分属于多余定义。

修正后的代码

import pygame

pygame.init()

wn = pygame.display.set_mode((200,200))

x = 100
y = 100

# 类名遵循Python大驼峰命名规范
class Circle():
    def __init__(self, x, y):
        self.x = x
        self.y = y
    # 移除冗余的x、y参数
    def draw(self):
        pygame.draw.circle(wn, (255, 0, 0), (self.x, self.y), 5)

# 先创建Circle类的实例
my_circle = Circle(x, y)
# 通过实例调用draw方法
my_circle.draw()

# 补充Pygame事件循环,避免窗口一闪而过
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
pygame.quit()

修正说明

  • 调整类名为Circle,符合Python代码规范(非强制,但建议遵守)。
  • 移除draw方法的冗余参数,直接使用实例初始化时保存的坐标。
  • 先实例化Circle类,再调用实例的draw方法,这是Python类方法调用的正确方式。
  • 增加事件循环,保证Pygame窗口能正常显示直到手动关闭。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 01:17:37