simple question
Joonas Paalasmaa
joonas at olen.to
Thu Aug 16 17:19:42 EDT 2001
Bignose3 wrote:
>
> 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):
> 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:)
Add the global statement to __init__ achieve the result simply.
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
>>> swimmer(1,2).swimmerID()
0
>>> swimmer(1,2).swimmerID()
1
>>> swimmer(1,2).swimmerID()
2
>>> swimmer(1,2).swimmerID()
3
More information about the Python-list
mailing list