Python如何处理正确设置了条件的结果变量

2024-10-02 08:21:20 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下几点:

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

    def main():
        outcome = funcA()

如果'some process'部分的结果是1,那么var dynamicVar将作为outcome传递回main func。如果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 

Tags: noreturnifmaindefsomeprocessdo
2条回答

在Python中,所有不返回值的函数都将隐式返回None。所以你可以在main()中检查if outcome is not None。你知道吗

我相信当你写一个函数时,它的返回值应该是清晰的和预期的。你应该把你说要归还的东西归还。也就是说,您可以使用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 ""

相关问题 更多 >

    热门问题