Python:流程避免嵌套的IF语句

时间:2016-07-28 13:44:16

标签: python python-2.7 design-patterns

我有一个进程(类),我分成几个步骤(方法)。只有前一个步骤成功,才能调用每个步骤。我创建了一个方法run(),通过在调用下一个步骤之前检查每个步骤来运行该过程:

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语句?

非常感谢,

3 个答案:

答案 0 :(得分:10)

您可以将步骤放在列表中:

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

答案 1 :(得分:0)

如果您没有太多的步骤,或者您不想将步骤函数放在一个序列中,这是一种替代方法。

def run(self):
    status = step_1():
    if status:
        status = step_2():
    if status:
        status = step_3():

    etc... [several IFs]

    if status is False:
        self.logger.error('Error')

    return status

答案 2 :(得分:-2)

将其视为未能返回False而不是传递返回True。

+----+---------------------+---+---------------------+----+-------------+
|user|user_time            |bus|bus_time             |stop|bus_time_diff|
+----+---------------------+---+---------------------+----+-------------+
|A   |2016-07-18 12:00:00.0|1  |2016-07-18 11:59:40.0|sA  |20           |
|A   |2016-07-18 12:00:00.0|1  |2016-07-18 11:59:50.0|sB  |10           |
|A   |2016-07-18 12:00:00.0|1  |2016-07-18 12:00:05.0|sC  |5            |
|B   |2016-07-19 12:00:00.0|2  |2016-07-19 11:59:40.0|sB  |20           |
|B   |2016-07-19 12:00:00.0|2  |2016-07-19 12:00:10.0|sC  |10           |
|C   |2016-07-20 12:00:00.0|3  |2016-07-20 11:59:55.0|sD  |5            |
|C   |2016-07-20 12:00:00.0|3  |2016-07-20 12:00:10.0|sE  |10           |
+----+---------------------+---+---------------------+----+-------------+
+----+---------------------+---+---------------------+----+-------------+----+
|user|user_time            |bus|bus_time             |stop|bus_time_diff|rank|
+----+---------------------+---+---------------------+----+-------------+----+
|A   |2016-07-18 12:00:00.0|1  |2016-07-18 12:00:05.0|sC  |5            |1   |
|B   |2016-07-19 12:00:00.0|2  |2016-07-19 12:00:10.0|sC  |10           |1   |
|C   |2016-07-20 12:00:00.0|3  |2016-07-20 11:59:55.0|sD  |5            |1   |
+----+---------------------+---+---------------------+----+-------------+----+