Subclasses in Python

Roy Smith roy at panix.com
Thu Apr 22 23:14:51 EDT 2004


tkpmep at hotmail.com (Thomas Philips) wrote:
> I'm teaching myself programming using Python

I'm not sure how to parse that.  Do you mean, "I'm teaching myself 
programming, and I'm using Python", or do you mean, "I already know how 
to program, and now I'm teaching myself Python"?

> and have a question about subclasses. My game has two classes, Player 
> and Alien, with identical functions, and I want to make Player a base 
> class and Alien a derived class.
> [...]
> The two classes are almost identical, except that:
> 1. When a new player is instantiated or destroyed, Player.n is
> incremented/decremented, while when a new alien is instantiated,
> Alien.n is incremented/decremented.

It sounds from your description that you really want Player and Alien to 
both be subclasses of a common base class.  The reason I say that is 
because Player.n doesn't get incremented when you create an Alien.

> 2. When hit by an energy blast, the player and the alien have
> different thresholds below which they die.

Again, this sounds like two subclasses of a common base class; let's 
call it Humanoid.  It sounds like hit() and blast() belong in Humanoid, 
and the "n" attribute should be a class variable of Alien and Player, 
each of which have their own __init__().

It's not clear what to do with "self.strength = 100" which currently 
you've got in each Player.__init__() and Alien.__init__().  One 
possibility is that you could factor this out into Humanoid.__init__(), 
and have each of the subclass's __init__() call Humanoid.__init__ 
(self).  The other possibility is to just leave it in each subclass's 
__init__() and not have a base class __init__() at all.  The XP folks 
would yell "refactor mercilessly", but in this case I'm not sure it's 
justified.

BTW, there's nothing in the above that's specific to Python.  The same 
arguments would work in pretty much any OOPL.



More information about the Python-list mailing list