[Tutor] Please explain part of this code
Jim
jf_byrnes at comcast.net
Wed Feb 15 17:37:45 EST 2017
import sys
from notebook import Notebook, Note
class Menu:
'''Display a menu and respond to choices when run.'''
def __init__(self):
self.notebook = Notebook()
self.choices = {
"1": self.show_notes,
"2": self.search_notes,
"3": self.add_note,
"4": self.modify_note,
"5": self.quit
}
def display_menu(self):
print("""
Notebook Menu
1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")
def run(self):
'''Display the menu and respond to choices.'''
while True:
self.display_menu()
choice = input("Enter an option: ")
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
<snip>
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 sort of understand what is going on with "action". All of the choices
to the right of the :'s are methods defined elsewhere in the code. So I
guess that will call whatever method is associated with a choice.
I don't recall ever seeing this before. What is this technique called?
Thanks, Jim
More information about the Tutor
mailing list