1

我正在学习python课程。我已经在我们的论坛中询问过这方面的提示,但没有成功。我认为我的实施非常糟糕。我对此陌生,所以请耐心等待,即使我提出问题的方式也是如此。

上面的问题是我被告知我需要做的。我试过没有运气,所以我来这里寻求帮助。

最终,我试图让我的键处理程序响应我的按键。我以前做过,但我们还没有使用类。这就是障碍所在。我应该实现类方法/变量以使其工作,而不是使用新变量或新全局变量。

例如

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
        ...

下面的处理程序在 SuchAndSuch 类之外:

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???

    ...

因此,所有更新都应该发生在 SuchAndSuch 类中,并且只有对这些更新的调用才应该在我的密钥处理程序中。

有人可以给我一个例子,说明他们说这句话时的意思吗?我尝试在我的关键处理程序中将所有变量(或论坛中给出的想法)错误实现为“未定义”。

4

1 回答 1

8

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()
于 2013-06-05T15:24:09.807 回答