0

In order to call a function using dictionary we use the following code:

def f1():
    print ("One")

def f2():
    print ("Two")

def f3():
    print ("Three")

dict = {1: f1, 2: f2, 3: f3}

dict[1]()

How does the last line dict[1]() actually works?

  • 4
    `dict[1]` is `f1`. So performing `dict[1]()` performs `f1()` . – khelwood Jun 09 '18 at 19:18
  • After you create your dict do this: `print(dict[1])`, you will see that you will get something along the lines of: ``. That is pretty much your uncalled function. To actually *call* it, this is where you do the `()` and you will see the result you are expecting. – idjaw Jun 09 '18 at 19:28
  • class NoneType(object) | Methods defined here: | | __hash__(...) | x.__hash__() <==> hash(x) | | __repr__(...) | x.__repr__() <==> repr(x) – Eddwin Paz Jun 09 '18 at 19:29
  • 1
    @eddwinpaz That is very confusing for the reader. If you want to provide an answer showcasing code, post the answer. Putting that in the comments is very hard to decipher. – idjaw Jun 09 '18 at 19:29

1 Answers1

0

Functions in Python are first class objects. This means that functions are objects that can be sent as parameters, they can be stored in data structures and you can do with them same as simple objects. You can read about them here.

Tudor Plugaru
  • 347
  • 2
  • 10
  • You want to add something to the effect of @khelwood's comment that `dict[1] is f1`, hence calling `dict[1]()` is `f1()` – smci Jun 10 '18 at 01:12