<html><head></head><body>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.<br>
<br>
It would work something like this:<br>
<br>
class Swimmer :<br>
next_ID = 0<br>
<br>
def __init__(self, xpos, ypos):<br>
self.xpos = xpos<br>
self.ypos = ypos<br>
<br>
self.swimmer_ID = Swimmer.next_ID<br>
#The next line also works but I think the top one is clearer.<br>
#self.swimmer_ID = self.next_ID<br>
Swimmer.next_ID += 1<br>
<br>
def __str__ (self) :<br>
return "xpos = %f\nypos = %f\nID = %d" % (self.xpos, self.ypos, self.swimmer_ID)<br>
<br>
<br>
a_swimmer = Swimmer(2, 4)<br>
b_swimmer = Swimmer(5,-10)<br>
c_swimmer = Swimmer(3.1415, 2.73)<br>
<br>
print a_swimmer<br>
print b_swimmer<br>
print c_swimmer<br>
<br>
<br>
<br>
<br>
Bjorn Pettersen wrote:<br>
<blockquote type="cite" cite="mid:6957F6A694B49A4096F7CFD0D900042F6C9DC8@admin56.narex.com">
<blockquote type="cite"><pre wrap="">From: Bignose3 [<a class="moz-txt-link-freetext" href="mailto:k98jh01@kzoo.edu">mailto:k98jh01@kzoo.edu</a>]<br><br>I am a student starting to learn python coming from a C++ background.<br>I am writing a simple simulation program were I am trying to assign<br>each "swimmer" an ID. Unfortunatley the way I would do it in C++<br>doesnt work for python. Can someone guide me in the right direction.<br><br>Here is the code that doesnt work, see what I am trying to do:<br><br>nextID= 0<br>class swimmer:<br> def __init__(self, xpos, ypos):<br></pre></blockquote>
<pre wrap=""><!---->+ global nextID<br></pre>
<blockquote type="cite"><pre wrap=""> self.ID = nextID<br> nextID= nextID + 1<br> self.xpos= xpos<br> self.ypos= ypos<br> def xcord(self):<br> print self.xpos<br> def ycord(self):<br> return self.ypos<br> def swimmerID(self):<br> return self.ID<br><br>An explanation would be great to. Not a complex program but you have<br>to start somewhere:)<br></pre></blockquote>
<pre wrap=""><!----><br>If you're going to assign to global variables, you'll need to let Python<br>know that you're talking about the global and not trying to create a new<br>local variable with the same name.<br><br>-- bjorn<br><br></pre>
</blockquote>
<br>
</body></html>