简体   繁体   中英

How to inherit specific variables from one class to another class?

I'm making a game in python using the pygame module and I wish to inherit one specific variable from one class to another class, but have no clue how. I have tried super() but it has not worked, however, me being a novice may just mean I did it wrong so please do not discount that as a possibility if it works.

I have listed which variable I wish inherited in the code below as well.

Here's my relevant code below:

Class I want to inherit FROM:

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 that I want to receive the inheritance:

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

Any help would be greatly appreciated, thank you.

You have to invoke the constructor of the base class. See super() :

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

Note the arguments for width and height are unclear in you example, so I've exemplarily used (10, 10).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM