Will Da Silva
Will Da Silva

Reputation: 7040

How to remove repetition between similar python classes

I currently have two classes: Block and Pic

Unfortunately they are almost identical. I'm looking for the best way to remove the repeated parts across the two classes.

class Block(pygame.sprite.Sprite):

    def __init__(self, colour, width, height):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface([width, height])
        self.image.fill(colour)

    def invert(self):
        self.image = inverted(self.image)

    def set_speed(self, speed):
        self.speed = speed

class Pic(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load('icon.png').convert()

    def invert(self):
        self.image = inverted(self.image)

    def set_speed(self, speed):
        self.speed = speed

Upvotes: 2

Views: 131

Answers (2)

arx5
arx5

Reputation: 336

Use class inheritance, i.e. create a class with the common parts and class methods and derive your classes Block and Pic from this new class.

Some examples are given here: http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/

Upvotes: 3

timgeb
timgeb

Reputation: 78760

How about creating a common base class?

class BaseClass(pygame.sprite.Sprite):
    'baseclass for your derived classes, feel free to choose a better name'
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

    def invert(self):
        self.image = inverted(self.image)

    def set_speed(self, speed):
        self.speed = speed

class Block(BaseClass):
    def __init__(self, colour, width, height):
        super(Block, self).__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(colour)

class Pic(BaseClass):
    def __init__(self):
        super(Pic, self).__init__()
        self.image = pygame.image.load('icon.png').convert()

Upvotes: 3

Related Questions