<p>好吧,尤其是如果你想扩展这个程序,我建议你使用如下方法:</p>
<pre><code>from itertools import islice
class Diagnosis:
diagnoses = ("You are Hypchondriac", "You have a Head Cold",
"You have an ear infection", "You have the flu", "You have the measles"
)
def __init__(self):
self.diagnosis = 0 # Consider using an enum for this
self.queue = (self.check_fever, self.check_nose, self.check_rash,
self.check_ear)
def ask(self, question):
answer = input(question + " [y/N] ").lower()
return answer != "" and answer[0] == "y"
def make(self):
queue_iter = iter(self.queue)
for func in queue_iter:
skip = func()
# return -1 if you want to break the queue
if skip == -1:
break
if skip > 0:
next(islice(queue_iter, skip, skip + 1))
def check_fever(self):
return 1 if self.ask("Do you have a fever?") else 0
def check_nose(self):
if self.ask("Do you have a stuffy nose?"):
self.diagnosis = 1
return -1
def check_rash(self):
if self.ask("Do you have a rash?"):
self.diagnosis = 4
return -1
return 0
def check_ear(self):
if self.ask("Does your ear hurt?"):
self.diagnosis = 2
else:
self.diagnosis = 3
return -1
def get_result(self):
return self.diagnoses[self.diagnosis]
if __name__ == "__main__":
diagnosis = Diagnosis()
diagnosis.make()
print("Diagnosis: " + diagnosis.get_result())
</code></pre>
<p>基本上,将您需要的所有函数放入队列中,并返回要跳过的函数数,如果完成了返回-1。在</p>