You need to enable JavaScript to run this app. Python+Pygame开发类继承报错:walker对象无draw属性问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Python+Pygame开发类继承报错:walker对象无draw属性问题求助

问题根源

你的draw、updateGravity、walk三个方法缩进错误,被定义在了__init__构造函数的内部,不属于generic类的成员方法,所以子类walker继承不到,实例自然找不到对应属性。

修复方法

调整genericEnemy.py中三个方法的缩进层级,让它们和__init__方法平级,属于generic类的成员即可:

'''
    This class controls generic capabilities for all enemies.
    Specific abilities are in the enemy type's class in the superfolder
'''

import pygame

class generic:
    def __init__(self, speed, pos, size):
        '''
            speed - The entity speed, an int greater than 0
            pos - The (x,y) position of the entity, a list of length 2
            size - The entity hitbox, a list with length 2
        '''

        #Movement Variables
        self.speed = speed
        self.currDir = 1
        self.isMoving = True

        #Drawing Variables
        self.pos = pos
        self.size = size

        #Gravity Variables
        self.isJumping = False
        self.fallCounter = 0
        self.gravityTimer = 0

#==================================================
    # 调整缩进和__init__对齐,成为类的成员方法
    def draw(self, surface):
        pygame.draw.rect(surface, (255, 0, 0), (self.pos[0], self.pos[1], self.size[0], self.size[1]))

#==================================================
    # 同样调整缩进
    def updateGravity(self):
        self.fallCounter += 1
        
        if self.fallCounter == 8:
            self.fallCounter = 0
            self.gravityTimer += 1

#==================================================
    # 同样调整缩进
    def walk(self):
        if self.isMoving:
            self.pos[0] += self.speed * self.currDir

小提示:Python对缩进非常敏感,定义类成员方法时,需要保证方法的缩进层级和构造方法__init__保持一致,不要缩进进其他方法的内部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 09:33:01