Subclasses in Python

Shalabh Chaturvedi shalabh at cafepy.com
Fri Apr 23 04:23:51 EDT 2004


Thomas Philips wrote:

> I'm teaching myself programming using 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 described below

<code defining classes Player and Alient snipped, but op's descrition
follows>

> 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.
> 2. When hit by an energy blast, the player and the alien have
> different thresholds below which they die.
> 
> How can I base the Alien's __init__(), __del__() and hit() methods on
> the Player's methods, while ensuring that the appropriate class
> variables are incremented/decremented when a new object is
> instantiated and that the appropriate threshold is used when the
> player/alien is hit by an energy bolt?
> 
> Thomas Philips

One easy solution is to use self.__class__.n and self.__class__.threshold
instead of explicit Player.n and Player.threshold. Then derive Alien from
Player and only keep the two class attributes in it. Get rid of all methods
in Alien.

If you haven't already guessed how this works: when you call any method on
an Alient object, self.__class__ will be Alien, and if you call a method on
a Player object, self.__class__ will be Player.

--
Shalabh





More information about the Python-list mailing list