I have a method in a Pygame Sprite subclass, defined as such:
def walk(self):
"""move across screen"""
displacement = self.rect.move((self.move, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
self.move = -self.move
displacement = self.rect.move((self.move, 0))
self.rect = displacement
I modified it, adding a parameter speed_x, and now the program is broken.
def walk(self, speed_x):
"""move across screen"""
displacement = self.rect.move((speed_x, 0))
if self.rect.left < self.area.left or self.rect.right > self.area.right:
speed_x = -speed_x
displacement = self.rect.move((speed_x, 0))
self.rect = displacement
Before I called the method like this:
def update(self):
self.walk()
Now I do:
def update(self):
self.walk(self.move)
Why doesn’t this work?
You don’t explain how it’s “broken”, but the main difference is that
which you have in your second version, is only changing the local variable (arguments are local variables!)
speed_x, so that changed value does not persist.In the first version,
does alter
self(specifically one of its attriubtes) and the alteration “persists” in future method calls on the object which is here accessed asself.Just one of the many key differences between bare names (like
speed_x) and qualified names (lineself.move), and, I suspect, what’s biting you here (hard as you may make it to guess by not saying how the second version is failing your expectations).