Subclasses in Python

Thomas Philips tkpmep at hotmail.com
Thu Apr 29 10:39:53 EDT 2004


I followed Shalabh's suggestion and rewrote Alien as a subclass of
Player, and used self.__Class__.<whatever I need to access> to access
the class attributes in the class and subclass. Works like a charm,
but I'm having some difficulty printing class names. I want
self.__class__ to return just the name of the class without some
ancillary stuff thrown in. A snippet of code follows:

class Player(object):
    #Class attributes for class Player
    threshold = 50
    initial_strength=100
    n=0

    #Private methods for class Player
    def __init__(self,name):
        self.name = name
        self.strength = self.__class__.initial_strength
        self.__class__.n +=1
        print self.__class__

            
class Alien(Player):
    #Class attributes for subclass Alien
    threshold = 30
    initial_strength=150
    n=0

When a new object is instantiated, the print statement in __init__
gives me
<class '__main__.Player'>
or
<class '__main__.Alien'>
How can I just get it to return

Player
or
Alien

Interestingly, if I do a class comparison of the form

if self.__class__== Alien:
    foo
elif self.__class__== Player
    bar

The comparison proceeds correctly. How can I get it to print the class
name cleanly? Do I have to convert <class '__main__.Alien'> to a
string and then use one or more string functions to clean it up?

Thomas Philips



More information about the Python-list mailing list