python避免深度嵌套的if-else_Python:处理流程避免嵌套的IF语句

1586010002-jmsa.png

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

Is there a more elegant way (a design pattern?) to avoid these nested IF statements?

Thanks a lot,

解决方案

You would place your steps in a list:

my_plan = (step1, step2, step3, ..., stepN)

And then execute them in a loop:

for step in my_plan:

if not step():

print 'Error in %s' % step.__name__

status = False

break

else:

status = True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值