Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reproduce a C function pointer array in Python

Tags:

python

c

I have a Python program asking the user for input like a shell, and if I detect some specific keywords I want to go inside some specific functions.

The thing is that I would like to avoid doing a lot of if and else if. Usually in C to avoid this situation I use a function pointer array that I travel with a while and use strcmp to check the input.

I would like to know how to do that in Python if it is even possible.

like image 395
Roger Avatar asked May 13 '15 20:05

Roger


Video Answer


1 Answers

In Python you use a dictionary.

Example:

keyword2func = {
    "word1": function_word1,
    "word2": function_word2,
}

word = input("")
keyword2func[word]()
like image 82
Daniel Avatar answered Oct 26 '22 07:10

Daniel