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

标签 python oop methods callback

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

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

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

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()

我认为静态方法不起作用,因为我的类将有多个实例。

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

#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 参数来使其运行,因为这是一种非静态方法(因此至少需要一个参数)。

关于python - 将类方法作为回调传递(面向对象编程 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31255351/

相关文章:

python - 如何做具有时间值(value)的报表

java - 将对象转换为子类对象而不丢失对该对象的引用

.net - 为什么我必须在这里使用重载?

ruby - “respond_to ?' versus '定义了吗?”

javascript - 方法、函数和对象

Java抽象类通过声明新方法继承

Python:从回调访问对象属性

python - Numpy 数组是否可哈希?

python - 使用 ffmpeg 从 Python : why the sound is cut only when streaming into a mp4 file ? 进行流式视频合成

java - 继承和 LSP