0

考虑以下:

    def funcA():
        some process = dynamicVar
        if dynamicVar == 1:
            return dynamicVar
        else:
            print "no dynamicVar"

    def main():
        outcome = funcA()

如果“某些过程”部分的结果为 1,则 var dynamicVar 将作为outcome主函数传回。如果 dynamicVar 不是 1,则例程将失败,因为没有返回任何参数。

我可以将结果包装为一个列表:

    def funcA():
        outcomeList = []
        some process = dynamicVar
        if dynamicVar == 1:
            outcomeList.append(dynamicVar)
            return outcomeList
        else:
            print "no dynamicVar"
            return outcomeList

    def main():
        outcome = funcA()
        if outcome != []:
            do something using dynamicVar
        else:
            do something else!

或者也许作为字典项目。我能想到的两种解决方案中的每一种都涉及主/请求函数中的另一组处理。

这是处理这种可能性的“正确”方法吗?或者,还有更好的方法?

处理这个问题的正确方法是什么。我特别想尝试捕获try:/except:错误,因此在该示例中,用途是相反的,因此类似于:

    def funcA():
        some process = dynamicVar
        if dynamicVar == 1:
            return
        else:
            outcome = "no dynamicVar"
            return outcome 

    def main():
        try:
            funcA()
        except:
            outcome = funcA.dynamicVar 
4

2 回答 2

3

在 Python 中,所有不返回值的函数都将隐式返回None。所以你可以签到if outcome is not Nonemain()

于 2012-11-19T05:26:35.830 回答
2

我相信当你编写一个函数时,它的返回值应该是明确的和预期的。你应该归还你说你会归还的东西。话虽如此,您可以将None其用作有意义的返回值来指示操作失败或未产生任何结果:

def doSomething():
    """
    doSomething will return a string value 
    If there is no value available, None will be returned
    """
    if check_something():
        return "a string"

    # this is being explicit. If you did not do this,
    # None would still be returned. But it is nice
    # to be verbose so it reads properly with intent.   
    return None

或者您可以确保始终返回相同类型的默认值:

def doSomething():
    """
    doSomething will return a string value 
    If there is no value available, and empty string 
    will be returned
    """
    if check_something():
        return "a string"

    return ""

这通过一堆复杂的条件测试来处理这种情况,这些测试最终只是失败了:

def doSomething():
    if foo:
        if bar:
            if biz:
                return "value"
    return ""
于 2012-11-19T05:30:54.630 回答