Skip to main content
 首页 » 编程设计

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

2025年05月04日10落叶

我有一个过程(类),我将其分成几个步骤(方法)。每个步骤只有在前一个步骤成功时才能调用。我创建了一个方法 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 语句?

非常感谢,

请您参考如下方法:

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

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