当你不确切地知道如何描述它时,很难找到这个问题的答案......
处理一个相当深的(但是固定的)嵌套测试集的最惯用的方法是什么,你希望按顺序运行但是在第一个测试成功后立即终止?
而不是以下
选项1 :(导致压痕过多)def make_decision():
results = ... some code or function that returns a list or None
if results:
decision = random.choice(results)
else:
results = ... other code or function
if results:
decision = random.choice(results)
else:
results = ... other code or function
if results:
decision = random.choice(results)
else:
results = ... other code or function
if results:
decision = random.choice(results)
...etc.
else:
decision = None
print(decision)
return decision
选项2
另一种选择是尽早从函数返回,但我不确定这么多的回报分散在一起是好的做法,在这种情况下,我宁愿最后做一件事(例如print(decision))在返回之前:def make_decision():
results = ... some code or function that returns a list or None
if results:
return random.choice(results)
results = ... other code or function
if results:
return random.choice(results)
results = ... other code or function
if results:
return random.choice(results)
...etc.
else:
decision = None
return decision
选项3
最后,我可以使每个测试成为这里描述的单独函数,并迭代地调用它们,前提是每个测试函数都有相同的参数集。def test1(args):
...
def test2(args):
...
def test3(args):
...
def make_decision():
decision = None
for test in [test1, test2, test3, ...]:
results = test(args)
if results:
decision = random.choice(results)
break
print(decision)
return decision
这看起来最好,但我没有计划为每个测试创建一个函数,一些测试可以使用相同的函数但使用不同的参数完成,有些只是单行,而其他是多行。那么在开始循环之前我是否必须构建一个函数和参数列表?或者列出一些partial功能?
欢迎任何更好的建议(在我继续上面的选项3之前)