4

我正在编写一个代码,它试图深入挖掘输入对象并找出该对象内部的值。这是一个示例代码:

def GetThatValue(inObj):
    if inObj:
       level1 = inObj.GetBelowObject()
       if level1:
           level2 = level1.GetBelowObject()
           if level2:
               level3 = level2.GetBelowObject()
               if level3:
                  return level3.GetBelowObject()
    return None

在很多情况下,我最终都会遇到这些“倾斜的 if 条件”。我怎样才能避免这种情况?这看起来很脏,也是一种防御性编程。

4

2 回答 2

9

使用for循环:

def GetThatValue(inObj):
    for i in range(4):
        if not inObj:
            break # OR return None
        inObj = inObj.GetBelowObject()
    return inObj

更新

避免深度嵌套的 if 语句。检查例外情况,并提前返回。

例如,下面的嵌套ifs:

if a:
    if b:
        return c
return d

可以转换为扁平ifs:

if not a:
    return d
if not b:
    return d
return c
于 2014-02-24T07:15:28.087 回答
4
try:
    return monkey.TypeWriter().Manufacturer().Shareholders().EthnicDistribution()
except AttributeError:
    return None

试着去拿东西。如果它不起作用,您就知道其中一个级别丢失了。如果这些GetBelowObject调用实际上不是完全相同的方法,则此方法特别有效。

于 2014-02-24T07:23:23.373 回答