繁体   English   中英

Python传递对象函数和引用函数变量

[英]Python pass object function and reference funciton variables

假设我正在python中使用OpenGL。

通常您打个电话,例如

glutDisplayFunc(display)

其中display是您编写的功能。

如果我上课怎么办

class foo:
    #self.x=5
    def display(self, maybe some other variables):
        #run some code
        print("Hooray!, X is:", self.x)

我想通过该显示功能并打印“ Hooray!,X为:5”

我可以通过吗

h = foo()
glutDisplayFunc(h.display)

能行吗?

是的,您可以这样调用该函数:

h = foo()
glutDisplayFunc(h.display)

如果这是您的课程:

class Foo():
  def __init__(self):
    self.x = 5
  def display(self):
    print("hooray {}".format(self.x))

这是你的glut_display_func()

def glut_display_func(func):
  func()

你可以这样做:

foo = Foo()
foo.display()

glut_display_func(foo.display)

并得到相同的结果:

hooray 5
hooray 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM