is this the right way to do subclasses?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Nov 8 23:51:17 CET 2006


John Salerno a écrit :
> 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.
> 
> Thanks!
> 
> 
> 
> 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
> 
> 
> class Thief(Character):
> 
>     def __init__(self, name, strength, dexterity, intelligence):
>         Character.__init__(self, name, strength, dexterity, intelligence)
>         self.health += 1
>         self.dexterity += 1
> 
> 
> class Mage(Character):
> 
>     def __init__(self, name, strength, dexterity, intelligence):
>         Character.__init__(self, name, strength, dexterity, intelligence)
>         self.intelligence += 1

This is correct, and a good first start. Now there's effectively some 
boilerplate that we could get rid of using the template method pattern:

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._post_init()

     def _post_init(self):
         pass

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


class Thief(Character):
     def _post_init(self):
         self.health += 1
         self.dexterity += 1


class Mage(Character):
     def _post_init(self):
         self.intelligence += 1

HTH



More information about the Python-list mailing list