【问题标题】:Passing a class method as callback (Object-oriented programming Python)将类方法作为回调传递(面向对象编程 Python)
【发布时间】:2015-07-06 20:50:04
【问题描述】:

我正在使用 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.draw,它就会调用它。如果您需要更多信息,只需将其存储在 Drawer 对象中即可。附言您的 main_draw 和 draw 函数需要接受 self 参数(因为它们不是静态/类方法)。
  • 感谢@CrazyCasta 我做对了,只是忘记了方法中的自我。谢谢

标签: python oop methods callback


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多