kivy“实例”是什么?像 on_pressed(self,instance,pos)

jin*_*ppy 5 kivy kivy-language

我想知道instancekivy这个词是什么意思?

class CustomBtn(Widget):
    pressed = ListProperty([0, 0])

    def on_touch_down(self, touch):
         if self.collide_point(*touch.pos):
             self.pressed = touch.pos
             # we consumed the touch. return False here to propagate
             # the touch further to the children.
             return True
         return super(CustomBtn, self).on_touch_down(touch)

     def on_pressed(self, instance, pos):
         print ('pressed at {pos}'.format(pos=pos))
         print ('My callback is call from', instance)
Run Code Online (Sandbox Code Playgroud)

Pat*_*ick 5

Class CustomBnt“instance”是按下按钮时对象实例的名称和引用。它不必命名为“实例”。您也可以将其称为“obj”或“btn”或任何对您有意义的名称。

您可以使用它来收集有关按下的按钮的信息。instance.text将是按钮上的文本,例如用于print type(instance)找出“实例”是什么类型的对象。


zee*_*eez 2

instance没有特殊意义。该参数用于向方法传达哪个对象触发了事件。考虑附加到另一个类的事件的事件处理程序:

class MyLabel(Label):
    def pressed_handler(self, instance, pos):
        print ('pressed at {pos}'.format(pos=pos))
        print ('My callback is call from', instance)

a = CustomBtn()
b = MyLabel()
a.bind(on_pressed=b.pressed_handler)
Run Code Online (Sandbox Code Playgroud)

然后pressed_handler将通过参数知道哪个对象发送了事件instance