Python scoping problem

This topic is 3956 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I have the following code:
global mousepos
class SpaceGameWindow(window.Window):

...

def __init__(self, *args, **kwargs):
self.max_monsters = 20
mousepos  =[0,0]

...

def on_mouse_motion(self, x, y, dx, dy):
mousepos = [x,y]

def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
mousepos = [x,y]

def on_mouse_press(self, x, y, button, modifiers):

if (button == 1):
self.bullets.append(Bullet(mousepos,self.ship
, self.bullet_image
, self.height
, x=self.ship.x + (self.ship.image.width / 2) - (self.bullet_image.width / 2)
, y=self.ship.y))


but it gives me the following error on the line where I create the bullet object:
... in on_mouse_press
self.bullets.append(Bullet(mousepos,self.ship
NameError: global name 'mousepos' is not defined


I'm using python 2.5.1 Anyone have any ideas as to how I can solve my problem?

Share on other sites

In your class __init__ function, mousepos is only declared locally for that function. You have defined it the same way in the on_mouse_motion and on_mouse_drag functions as well.

In order to make mousepos a member of this class, you must explicitly define it as such. The easiest way would be to simply prefix all definitions of mousepos with 'self.'. Basically, do the same thing you did with self.max_monsters.

Share on other sites
I thought that made the variable local... Well, a bad misconception I guess... Thanks :D

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5
khawk
11

• 9
• 9
• 11
• 11
• 23
• Forum Statistics

• Total Topics
633677
• Total Posts
3013281
×