Subclasses in Python
Peter Otten
__peter__ at web.de
Thu Apr 29 12:26:20 EDT 2004
Thomas Philips wrote:
> 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__
make that
print self.__class__.__name__
> 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:
This compares two *classes* not classnames. Even classes with the same name
defined, say, in a function would be recognized as not equal:
>>> def makeClass():
... class A(object): pass
... return A
...
>>> A1 = makeClass()
>>> A2 = makeClass()
>>> A1
<class '__main__.A'>
>>> A2
<class '__main__.A'>
>>> A1 == A2
False
Now compare the names:
>>> A1.__name__, A2.__name__
('A', 'A')
>>> A1.__name__ == A2.__name__
True
>>>
> 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?
No, "<class '__main__.Alien'>" is the string that is generated when the
class Alien is converted to string. If you want something else you have to
change to a custom metaclass - better stick to Alien.__name__.
Peter
More information about the Python-list
mailing list