问题
I am new to Python and trying to create a user interface with options to insert, delete and update data. THe data will be manipulated in a text file. I wanted to accept option from user and call respective function to do the activity. One alternative that I found was to declare Dictionary The whole code is :
print("Select options from below")
dict_options = {'1' : 'Insert',
'2' : 'Update',
'3' : 'Delete',
'4' : 'Display_number_of_records',
'5' : 'Display_all_records',
'6' : 'Exit'}
for key in dict_options.keys():
value = dict_options.get(key)
print(str(key) + ". " + value)
option = input("Enter an option : ")
while (option != '6'):
value = dict_options.get(option)
dict_options[option]()
option = input("Enter an option : ")
def Insert():
print("Insert a record")
return`enter code here`
When I execute, it gives me an error:
TypeError: 'str' object is not callable at dict_options[option]()
回答1:
Strings, such as dict_options[option], are not callable, but functions are. Therefore, make the dict_options values be function objects:
Change
dict_options = {'1' : 'Insert',
'2' : 'Update',
'3' : 'Delete',
'4' : 'Display_number_of_records',
'5' : 'Display_all_records',
'6' : 'Exit'}
to
dict_options = {'1' : Insert,
'2' : Update,
'3' : Delete,
'4' : Display_number_of_records,
'5' : Display_all_records,
'6' : Exit}
Note you'll have to define the functions before defining dict_options.
Also, to print the name of the function, change value to value.__name__:
for key in dict_options.keys():
value = dict_options.get(key)
print(str(key) + ". " + value)
becomes
for key in dict_options.keys():
value = dict_options.get(key)
print(str(key) + ". " + value.__name__)
回答2:
EDIT: Looks like unutbu beat me to it.
This line:
dict_options[option]()
Evaluates to something like this:
'Some String'()
You cannot call a string like this (try it!). You'll have to edit your dictionary so the values inside are functions (or some other kind of callable object), not strings.
EDIT:
Assuming the string values in your dictionary are the names of callable objects (e.g. functions), you COULD make it work the way you have it using exec:
exec(dict_options[option] + '()')
However, this is BAD BAD! Do NOT do this!
来源:https://stackoverflow.com/questions/27742714/dictionary-str-object-is-not-callable