is this the right way to do subclasses?

Ben Finney bignose+hates-spam at
Thu Nov 9 02:35:09 CET 2006

John Salerno <johnjsal at> writes:

> 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.

This is another reason why passing the "stats" values as a mapping
object is a good alternative.

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

    class Character(object):
        stat_keys = ['strength', 'dexterity', 'intelligence']
        def __init__(self, name, stats):
   = name
   = 10
            self.stats = {}
            for (key, value) in [(k, stats.get(k)) for k in stat_keys]:
                setattr(self, key, value)

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

    class Fighter(Character):
        def __init__(self, name, stats):
            Character.__init__(self, name, stats)
   += 1
            self.strength += 1

et cetera.

All you need to do to add a new type of "stat" is to add a new item to
the 'stat_keys' list in Character.

 \      "I bought a self learning record to learn Spanish. I turned it |
  `\        on and went to sleep; the record got stuck. The next day I |
_o__)                could only stutter in Spanish."  -- Steven Wright |
Ben Finney

More information about the Python-list mailing list