is this the right way to do subclasses?

Peter Otten __peter__ at web.de
Wed Nov 8 14:19:39 EST 2006


John Salerno wrote:

> Ok, back to my so-called "game." I'm just curious if I've implemented
> the subclasses properly, because it seems like an awful lot of
> repetition with the parameters. And again, if I want to add a new
> attribute later, I'd have to change a lot of things. I can't help but
> get the feeling that I'm doing something very inefficiently.

> class Character(object):
> 
>      def __init__(self, name, strength, dexterity, intelligence):
>          self.name = name
>          self.health = 10
>          self.strength = strength
>          self.dexterity = dexterity
>          self.intelligence = intelligence
> 
> 
> class Fighter(Character):
> 
>      def __init__(self, name, strength, dexterity, intelligence):
>          Character.__init__(self, name, strength, dexterity, intelligence)
>          self.health += 2
>          self.strength += 1

One way to avoid the repetition:

class Character(object):
    def __init__(self, name, strength, dexterity, intelligence):
        self.name = name
        self.health = 10
        self.strength = strength
        self.dexterity = dexterity
        self.intelligence = intelligence
        self.fix_attributes()

class Fighter(Character):
    def fix_attributes(self):
        self.health += 2
        self.strength += 1

You may need a no-op implementation of fix_attributes() in the Character
class.

Peter




More information about the Python-list mailing list