What's the best way to write this base class?

Ian Kelly ian.g.kelly at gmail.com
Sat Jun 18 10:51:03 EDT 2011


On Sat, Jun 18, 2011 at 7:37 AM, bruno.desthuilliers at gmail.com
<bruno.desthuilliers at gmail.com> wrote:
> If you go that way, then using polymorphic dispatch might (or not,
> depending on the game's rules <g>) be a good idea:
>
>
> class Character(object):
>    BASE_HEALTH = 50
>    ...
>    def __init__(self, name):
>        ...
>        self.health = type(self).BASE_HEALTH

This of course is equivalent to a simple "self.health =
self.BASE_HEALTH" as long as you haven't explicitly assigned
BASE_HEALTH on the instance.

Tangentially, I wouldn't use inheritance at all for this game.  I know
the classic "is-a / has-a" test says that a wizard "is a" character,
but in my experience that method leans toward doing way too much
inheritance.  If you have subclasses for character classes, then you
will be tempted to also use subclasses for races, and then when you're
ready to make elf wizards you will have forced yourself into a
multiple inheritance situation, and down that path wait Agony and
Despair.

Instead, I would use composition here.  A character has a class (e.g.
Wizard(specialization='fire')) and a race (e.g. Elf(breed='high') --
or maybe just HighElf(), which inherits from Elf).  Save inheritance
for broad categories of what it means to be a character (e.g.
PlayerCharacter vs. NonPlayerCharacter or MobileCharacter vs.
MagicMirror, etc., any of which might have the Wizard character
class).

Cheers,
Ian



More information about the Python-list mailing list