如何将特定变量从一类继承到另一类?

时间:2020-02-10 20:55:41

标签: python class variables inheritance pygame

我正在使用pygame模块在python中制作游戏,我希望将一个特定的变量从一个类继承到另一个类,但不知道如何做。我已经尝试过super(),但是它没有用,但是,作为新手,我可能只是说我做错了,所以请不要小看它是否可行。

我也在下面的代码中列出了我希望继承哪个变量。

这是我下面的相关代码:

我要继承自的类:

class player():
    def __init__(self, x, y, width, height, walkCount):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 15
        self.lastDirection = "right" or "left" or "up" or "down" #<--- variable I want to inherit
        self.walkCount = walkCount

    def drawCharacter(self, window):
        dest = (self.x, self.y)
        if self.walkCount + 1 >= 30:
            self.walkCount = 0
        if self.lastDirection == "left":
            window.blit(protagL[0], dest)
        elif self.lastDirection == "right":
            window.blit(protagR[0], dest)
        elif self.lastDirection == "up":
            window.blit(protagU[0], dest)
        elif self.lastDirection == "down":
            window.blit(protagD[0], dest)

我要接收继承的类:

class projectile(player):
    def __init__(self, x, y, direction, travelCount):
        self.x = x
        self.y = y
        self.direction = direction
        self.vel = 20 * direction
        self.travelCount = travelCount

    def drawBullet(self, window):
        dest = (self.x, self.y)
        if self.travelCount + 1 >= 15:
            self.walkCount = 0
        if lastDirection == "right" or "left": # <---  I Want to call lastDirection variable here
            if self.travelCount < 15:
                window.blit(bulletsP[self.travelCount//3], dest) #dest)
                self.travelCount += 1
                self.x += self.vel

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您必须调用基类的构造函数。参见super()

class projectile(player):
    def __init__(self, x, y, direction, travelCount):
        super().__init__(x, y, 10, 10, travelCount)
        # [...]

请注意,在您的示例中,宽度和高度的参数不清楚,因此我示例性地使用了(10,10)。