将 class 方法作为回调传递(面向对象编程 Python)

Passing a class method as callback (Object-oriented programming Python)

我正在 python 使用 OpenGL 构建一个简单的游戏。

我通过 classes 构建我的逻辑,classes 生成信息并将其传递给 OpenGL。

不幸的是,OpenGL 正在使用回调,我不知道如何在此过程中使用我的 class 方法。

class Drawer(object):
    level = 0
    def main_draw():
        ...
        glutInit() 
        glutTimerFunc(interval, update, 0)          
        glutDisplayFunc(self.draw) #<----- here's my trouble
        glutIdleFunc(self.draw) #<----- here's my trouble
        ...

    def draw():
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()
        refresh2d_custom(width, height, field_width, field_height)

        #TODO
        draw_walls()

        glutSwapBuffers()

我认为静态方法行不通,因为我的 class 会有多个实例。

如果我直接使用函数,这似乎是迄今为止最简单的解决方案,我如何将实例传递到特定文件?

#draw.py

#instance that has been pass to this file. It is not instanciated in draw.py
#level would be global in this file
level = MyGameInstance.level 

self 参数添加到您的对象的函数中,您可以在对象被回调时访问您的对象。无论如何,self 参数都需要将其设置为 运行,因为这是一种非静态方法(因此至少需要一个参数)。