simple question

Matthew D. Wood woodm at equire.com
Thu Aug 16 17:15:13 EDT 2001


I wouldn't do it with global variables at all.  I would make nextID a 
variable of the CLASS not a variable of an INSTANCE.

It would work something like this:

class Swimmer :
       next_ID = 0

       def __init__(self, xpos, ypos):
               self.xpos = xpos
               self.ypos = ypos

               self.swimmer_ID = Swimmer.next_ID
               #The next line also works but I think the top one is clearer.
               #self.swimmer_ID = self.next_ID
               Swimmer.next_ID += 1

       def __str__ (self) :
               return "xpos = %f\nypos = %f\nID = %d" % (self.xpos, 
self.ypos, self.swimmer_ID)


a_swimmer = Swimmer(2, 4)
b_swimmer = Swimmer(5,-10)
c_swimmer = Swimmer(3.1415, 2.73)

print a_swimmer
print b_swimmer
print c_swimmer




Bjorn Pettersen wrote:

>> From: Bignose3 [mailto:k98jh01 at kzoo.edu]
>> 
>> I am a student starting to learn python coming from a C++ background.
>> I am writing a simple simulation program were I am trying to assign
>> each "swimmer" an ID.  Unfortunatley the way I would do it in C++
>> doesnt work for python.  Can someone guide me in the right direction.
>> 
>> Here is the code that doesnt work, see what I am trying to do:
>> 
>> nextID= 0
>> class swimmer:
>>     def __init__(self, xpos, ypos):
> 
> +         global nextID
> 
>>         self.ID = nextID
>>         nextID= nextID + 1
>>         self.xpos= xpos
>>         self.ypos= ypos
>>     def xcord(self):
>>         print self.xpos
>>     def ycord(self):
>>         return self.ypos
>>     def swimmerID(self):
>>         return self.ID
>> 
>> An explanation would be great to.  Not a complex program but you have
>> to start somewhere:)
> 
> 
> If you're going to assign to global variables, you'll need to let Python
> know that you're talking about the global and not trying to create a new
> local variable with the same name.
> 
> -- bjorn
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20010816/1c6f4dcd/attachment.html>


More information about the Python-list mailing list