1 回答
TA貢獻2041條經驗 獲得超4個贊
您的方法不起作用,因為您在構建字典時立即調用input()or函數。,例如,返回,這就是你得到錯誤的原因。time.sleep()time.sleep()None
當您從字典中檢索值并且實際上想要“慢打印”描述時,您需要稍后調用這些函數。
您可以通過多種不同的方式來做到這一點。你可以
使用字符串序列(例如列表或元組)而不是單個字符串,并讓您的
slowprint()函數接受序列并在打印每個元素后暫停。使用一系列字符串并混合特殊值來
slowprint()尋找做不同的事情,比如睡覺或請求輸入。在字典中存儲一個函數,然后調用。函數也是對象,就像字符串一樣。該函數將處理所有打印和暫停。
例如存儲一個字符串元組:
EXAMINATION: (
"The grass in this field is extremely soft.",
"The wind feels cool on your face.",
"The sun is beginning to set.",
)
然后讓你的slowprint()函數處理:
def slowprint(lines):
"""Print each line with a pause in between"""
for line in lines:
print(line)
input("> ") # or use time.sleep(2), or some other technique
第二個選項,插入特殊值,使您能夠將各種額外功能委托給其他代碼。您需要測試序列中對象的類型,但這會讓您在檢查描述中插入任意操作。就像睡覺和要求用戶擊鍵之間的區別一樣:
class ExaminationAction:
def do_action(self):
# the default is to do nothing
return
class Sleep(ExaminationAction):
def __init__(self, duration):
self.duration = duration
def do_action(self):
time.sleep(self.duration)
class Prompt(ExaminationAction):
def __init__(self, prompt):
self.prompt = prompt
def do_action(self):
return input(self.prompt)
并讓slowprint()函數查找這些實例:
def slowprint(examine_lines):
for action_or_line in examine_lines:
if isinstance(action_or_line, ExamineAction):
# special action, execute it
action_or_line.do_action()
else:
# string, print it
print(action_or_line)
您可以進行任意數量的此類操作;關鍵是它們都是子類ExamineAction,因此可以與普通字符串區分開來。將它們放入您的EXAMINATION密鑰序列中:
EXAMINATION: (
"The grass in this field is extremely soft.",
Prompt("> "),
"The wind feels cool on your face.",
Sleep(2),
"The sun is beginning to set.",
)
可能性是無止境。
添加回答
舉報
