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 -- http://mail.python.org/mailman/listinfo/python-list