问题
I'm taking python classes. I've asked for hints about this in our forums but with no luck. I think my implementation is very bad. I'm very new at this, so bear with me, even with the way I ask the question.
The question above is what I am told I need to do. I've tried but with no luck, so I've come here for help.
Ultimately, I am trying to get my key handlers to respond to my keypresses. I've done this previously, but we were not yet working with classes. That's where the snag is. I'm supposed to implement class methods/variables to make them work, not use new variables or new globals.
e.g.
class SuchAndSuch:
def __init__(self, pos, vel, ang, ang_vel, image, info, sound = None):
self.pos = [pos[0],pos[1]]
self.vel = [vel[0],vel[1]]
self.angle = ang
self.angle_vel = ang_vel
self.image = image
def update(self):
# this is where all the actual movement and rotation should happen
...
The handler below is outside the SuchAndSuch class:
def keydown(key):
# need up left down right buttons
if key == simplegui.KEY_MAP["up"]:
# i'm supposed to just call methods here to make the keys respond???
...
So, all updates are supposed to be happening in the SuchAndSuch class and only calls for this updates are supposed to be inside my keyhandler.
Can someone please give me an example on what they mean when they say this? All the variables (or ideas given in forums) I try to implement in my key handlers error as "undefined".
回答1:
There are two ways to call a class' methods from outside that class. The more common way is to call the method on an instance of the class, like this:
# pass all the variables that __init__ requires to create a new instance
such_and_such = SuchAndSuch(pos, vel, ang, ang_vel, image, info)
# now call the method!
such_and_such.update()
Simple as that! The self
parameter in the method definition refers to the instance that the method is being called on, and is implicitly passed to the method as the first argument. You probably want such_and_such
to be a module-level ("global") object, so you can reference and update the same object every time a key is pressed.
# Initialize the object with some default values (I'm guessing here)
such_and_such = SuchAndSuch((0, 0), (0, 0), 0, 0, None, '')
# Define keydown to make use of the such_and_such object
def keydown(key):
if key == simplegui.KEY_MAP['up']:
such_and_such.update()
# (Perhaps your update method should take another argument?)
The second way is to call a class method. This is probably not what you actually want here, but for completeness, I'll define it briefly: a class method is bound to a class
, instead of an instance of that class. You declare them using a decorator, so your method definition would look like this:
class SuchAndSuch(object):
@classmethod
def update(cls):
pass # do stuff
Then you could call this method without an instance of the class:
SuchAndSuch.update()
来源:https://stackoverflow.com/questions/16943582/how-do-i-use-a-method-outside-a-class