[Tutor] Please explain part of this code

Alan Gauld alan.gauld at yahoo.co.uk
Wed Feb 15 17:56:19 EST 2017


On 15/02/17 22:37, Jim wrote:

>          self.choices = {
>                  "1": self.show_notes,
>                  "2": self.search_notes,
>                  "3": self.add_note,
>                  "4": self.modify_note,
>                  "5": self.quit
>                  }
> 
> The author says:
> 
> The action variable actually refers to a specific method and is called 
> by appending empty brackets (since none of the methods require 
> parameters) to the variable.
> 

> I don't recall ever seeing this before.  What is this technique called?

Its very common, especially in GUIs and used in many
languages including C, VB, Java, Javascript and Lisp.
Its usually called a callback (because the stored
function is called back by the event receiver).

In C it is done by using a "pointer to a function".
In Lisp you create a Lambda (an anonymous function)
- which you can also do in Python and recent Java
versions. In Smalltalk and Ruby you define a "block".
In most of the other languages it's similar to Python,
you just pass the name of the function.

This is often referred to as the language treating
functions as "first class objects", and is a core
part of Functional Programming.

A common FP structure is the map function which takes
a function and a sequence and applies the function
to each member of the sequence, returning the
resultant sequence. Here is a short Python example:

def double(x): return x*2

data = [1,2,3,4]
result = map(double, data)   # -> [2,4,6,8]
print(result)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list