[英]Calling a function from dictionary via user input - ValueError raised more often than I want
[英]Python: Calling a function from a dictionary via user input
我正在嘗試使用字典鍵調用函數。 目前,詞典中只有一個功能,但我打算添加更多功能。 下面的代碼用於顯示列表,因為函數“ loadlist”沒有參數,並且在將文件打開為f時,我已將“ gameone.txt”寫入主體代碼中。
我想將文件名作為loadlist函數的參數,以便用戶輸入例如... loadlist('gameone.txt')或loadlist('gametwo.txt')等,具體取決於他們想要顯示的內容。
def interact():
command = raw_input('Command:')
def loadlist():
with open('gameone.txt', 'r') as f:
for line in f:
print line
dict = {'loadlist': loadlist}
dict.get(command)()
return interact()
相互作用()
我已經嘗試過下面的代碼,但無法解決問題。
def interact():
command = raw_input('Command:')
def loadlist(list):
with open(list, 'r') as f:
for line in f:
print line
dict = {'loadlist': loadlist}
dict.get(command)()
return interact()
相互作用()
感謝您的任何投入。
您可以嘗試使用* args。
def interact():
command,file_to_load = raw_input('Command:').split(' ')
# *args means take the parameters passed in and put them in a list called args
def loadlist(*args):
# get the argument from args list
filename = args[0]
with open(filename, 'r') as f:
for line in f:
print line
dict = {'loadlist': loadlist}
dict.get(command)(file_to_load)
interact()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.