Dan Hill
Dan Hill

Reputation: 43

How can I create a subclass of an existing class?

I'm creating a Space Invaders with PyGame, and I would like to create a subclass of the class Alien, to simplify my code a bit. How would I do this? This is the code i have so far:

class Alien(pygame.sprite.Sprite):
    def __init__(self, width, height):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(RED)
        self.image = pygame.image.load("alien1.png").convert_alpha()
        self.rect = self.image.get_rect()

Upvotes: 0

Views: 747

Answers (1)

kszl
kszl

Reputation: 1213

In fact, you've just created a subclass of Sprite. Just do the same with Alien.

class Reptilian(Alien):
    def __init__(self, width, height, human_form):  # you can pass some other properties
        super().__init__(width, height)  # you must pass required args to Alien's __init__
        # your custom stuff:
        self.human_form = human_form

Upvotes: 3

Related Questions