Main Content

What are callbacks? Why use them? An example in Python

Archive - Originally posted on "The Horse's Mouth" - 2016-02-11 08:38:42 - Graham Ellis

A callback is a function that's called from within another, having initially been "registered" for use at an outer level earlier on. Yeah, right - what does that mean or do?

An example ... if I'm setting up a GUI (Graphic User Interface), as I define my various sliders and buttons, I want to say "when this is pressed, do xxxx", but I don't actually want to do "xxxx" until the button is pressed - probably some considerabel time after the initial definition.

An example from this week's Python Course - see [here].

I've defined a couple of methods for running later such as:

  def inflate(value):
    return value * 1.7


I've passed those methods into an object

  john = thing(12,inflate)

and used a method I've chosen to call "perform" to run the method later:

  print(john.perform())

To complete the example, here's the class:

  class thing:
    def __init__(this,amount,action):
      this.amount = amount
      this.action = action
  
    def perform(this):
      return this.action(this.amount)