Python:处理流程避免嵌套的IF语句 [英] Python: process flow avoiding nested IF statements
本文介绍了Python:处理流程避免嵌套的IF语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个过程(类),我将其分为几个步骤(方法)。如果上一步成功,则只能调用每个步骤。我创建了一个方法run(),通过在调用下一个步骤之前检查每个步骤来运行该过程:
I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:
def run(self):
status = False
if step_1():
if step_2():
if step_3():
etc... [several nested IFs]
status = True
else:
self.logger.error('Error in step 3')
else:
self.logger.error('Error in step 2')
else:
self.logger.error('Error in step 1')
return status
有没有更优雅的方法(设计模式?)来避免这些嵌套的IF语句?
Is there a more elegant way (a design pattern?) to avoid these nested IF statements?
非常感谢,
推荐答案
您将把步骤放在列表中:
You would place your steps in a list:
my_plan = (step1, step2, step3, ..., stepN)
然后循环执行它们:
for step in my_plan:
if not step():
print 'Error in %s' % step.__name__
status = False
break
else:
status = True
这篇关于Python:处理流程避免嵌套的IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文