473,574 Members | 2,281 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subclasses in Python

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

class Player(object):
#Class attributes for class Player
threshold = 50
n=0 #n is the number of players

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

def __del__(self):
Player.n -=1
print "You got me, Alien"

#Public methods for class Player
def blast(self,enem y,energy):
enemy.hit(energ y)

def hit(self,energy ):
self.strength -= energy
if(self.strengt h <= Player.threshol d):
self.__del__()

class Alien(Player):
#Class attributes for class Alien
threshold = 100
n=0 #n is the number of players

#Private methods for class Alien
def __init__(self,n ame):
self.name = name
self.strength = 100
Alien.n +=1

def __del__(self):
Alien.n -=1
print "You got me, earthling"

#Public methods for class Alien
def hit(self,energy ):
self.strength -= energy
if(self.strengt h <= Alien.threshold ):
self.__del__()

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
Jul 18 '05 #1
5 2889
tk****@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.stren gth = 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.
Jul 18 '05 #2
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.threshol d. 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
Jul 18 '05 #3
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_strengt h=100
n=0

#Private methods for class Player
def __init__(self,n ame):
self.name = name
self.strength = self.__class__. initial_strengt h
self.__class__. n +=1
print self.__class__
class Alien(Player):
#Class attributes for subclass Alien
threshold = 30
initial_strengt h=150
n=0

When a new object is instantiated, the print statement in __init__
gives me
<class '__main__.Playe r'>
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
Jul 18 '05 #4
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_strengt h=100
n=0

#Private methods for class Player
def __init__(self,n ame):
self.name = name
self.strength = self.__class__. initial_strengt h
self.__class__. n +=1
print self.__class__
make that
print self.__class__. __name__
class Alien(Player):
#Class attributes for subclass Alien
threshold = 30
initial_strengt h=150
n=0

When a new object is instantiated, the print statement in __init__
gives me
<class '__main__.Playe r'>
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

Jul 18 '05 #5
You have needed edit already. To explain a bit more ...
#Private methods for class Player
def __init__(self,n ame):
self.name = name
self.strength = self.__class__. initial_strengt h
self.__class__. n +=1
print self.__class__
print object # is same as
print str(object) # ie, prints stringifies everything
Interestingly, if I do a class comparison of the form

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

The comparison proceeds correctly.
Here self.__class__ is left as the class object, as usual, and not
stringified.
How can I get it to print the class
name cleanly? Do I have to convert <class '__main__.Alien '> to a
string
That is what you did to print it '-)
and then use one or more string functions to clean it up?


Fortunately not.

Terry J. Reedy


Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1333
by: Kenneth McDonald | last post by:
I've recently used subclasses of the builtin str class to good effect. However, I've been unable to do the following: 1) Call the constructor with a number of arguments other than the number of arguments taken by the 'str' constructor. 2) Create and use instance variables (eg. 'self.x=1') in the same way that I can in a 'normal' class. ...
1
2287
by: Edward Loper | last post by:
I'm having trouble pickling subclasses of dict when they contain cycles. In particular: >>> import pickle >>> class D(dict): pass >>> d = D() >>> d = d # add a cycle. >>> print d {1: {...}} >>> pickle.dump(d, open('d.pickle', 'w'))
0
1296
by: Vera | last post by:
Hi, I have a very annoying problem, with which I NEED HELP DESPERATELY!! It smells like a bug to me, but I'm not sure. SITUATION This description is a very much simplified version of the real situation. I have the following class structure: ASSEMBLY ATools
8
2996
by: Marco | last post by:
Hi all, I have a base class and some subclasses; I need to define an array of objects from these various subclasses. What I have is something like: { //I have a base class, something like: class CPeople {
2
4408
by: MR | last post by:
I'm hoping that someone here will be able to direct me to some litrature on how to get a list of a classes subclasses. I.e. need the inherited class to know about subclasses that are inherited form it. I guess that I'll have to use reflection but I can't find any examples on MSDN. Thanks in advance, Mark
9
2141
by: Ulrich Hobelmann | last post by:
Hi, slowly transitioning from C to C++, I decided to remodel a struct/union (i.e. type identifier as first field, union of variant types) as a class + subclasses. Switching functions are replaced by virtual functions. So far so good. Now what I used to do is have a struct, set its type and union member, and return a pointer. I.e. I...
7
2069
by: Daniel Nogradi | last post by:
What is the simplest way to instantiate all classes that are subclasses of a given class in a module? More precisely I have a module m with some content: # m.py class A: pass class x( A ): pass
2
1511
by: Létezõ | last post by:
I use Python 2.4.4. Please read the code below: ----------------------------------------------------------- from new import classobj def mymeta(name,bases,clsdict): print 'meta: %s'%name return classobj(name,bases,clsdict) class A(object):
10
2265
by: Karlo Lozovina | last post by:
Hi, what's the best way to keep track of user-made subclasses, and instances of those subclasses? I just need a pointer in a right direction... thanks. -- Karlo Lozovina -- Mosor
0
7797
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7715
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7806
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8093
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5611
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5296
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3739
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2233
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1053
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.