Python:尝试使用 pygame 的多态性

Python: Trying to use polymorphism with pygame

我正在尝试在我的 pygame 项目中使用多态性,但我总是遇到错误。

我有一个 Moveable class 和一个继承自 Moveable 的 Objects class,我得到一个 AttributeError: 'NoneType' object has no attribute 'ypos' 在我的游戏循环中.

我计划在我的项目中加入更多可移动的对象,例如人、房屋、路标...如果我能做到这一点。

class Moveable:
    __name = ""
    __xpos = 0
    __ypos = 0
    __hight = 0
    __width = 0
    __speed = 0
    __image = 0

    def __init__(self, xpos, ypos, hight, width, speed, image):
        self.__xpos = xpos
        self.__ypos = ypos
        self.__hight = hight
        self.__width = width
        self.__image = image

    def set_xpos(self, xpos):
        self.__xpos = xpos

    def get_xpos(self):
        return self.__xpos

    # ... and all my other getters and setters...


class Objects(Moveable):

    def car(xpos, ypos, width, hight, speed, image):
        pygame.Surface.blit(gameDisplay, image, [xpos, ypos, hight, width])

def game_loop():

game_exit = False #sets the game loop to false

while not game_exit: # runs the game loop until the game exit = true

    car = Objects.car(random.randrange(250, 550), -400, 60, 70, 4, pygame.image.load('car.png'))
    gameDisplay.blit(backGroundImg, (0, 0)) #displays the background
    car.ypos += car.speed # the error is here **********

r

你需要 return pygame 如果这是你的意图。

def car(xpos, ypos, width, hight, speed, image):
    return pygame.Surface.blit(gameDisplay, image, [xpos, ypos, hight, width])

就目前而言,car 没有 return 语句,因此将变量分配给该方法将 return None,因此您在尝试访问属性时出错在 NoneType