5

I would like to know what does the word instance mean in kivy?

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)
zeeMonkeez
  • 5,057
  • 3
  • 33
  • 56
jinghappy
  • 51
  • 1
  • 4

2 Answers2

5

'instance' is the name and reference to the object instance of the Class CustomBnt when you press the button. It does not have to be named 'instance'. You may also call it 'obj' or 'btn' or whatever makes sense to you.

You use it to gather information about the pressed Button. instance.text would be the text on the Button e.g. Use print type(instance) to find out what kind of object 'instance' is.

Patrick
  • 131
  • 4
2

instance does not have a special meaning. This argument is used to convey to the method which object triggered an event. Consider an event handler attached to an event from another class:

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)

then pressed_handler will know which object sent the event, through the instance argument.

zeeMonkeez
  • 5,057
  • 3
  • 33
  • 56