【问题标题】:Python - how to handle outcome variables that are conditional set correctlyPython - 如何处理正确设置条件的结果变量
【发布时间】:2012-11-07 00:55:13
【问题描述】:

考虑以下几点:

    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 

【问题讨论】:

  • 您在这里要解决的实际问题是什么?如果您不返回任何内容,则返回None
  • 我添加了我试图解决的问题作为示例
  • @JayGattuso 究竟是如何“例行公事失败”的?您发布的代码在我看来完全没问题...
  • @deathApril 如果 dynamicVar 确实 = 1,则没有要分配给 outcome(在 main() 中)的返回参数。

标签: python


【解决方案1】:

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

【讨论】:

  • 啊,好的!我可以返回对象None 并对此进行评估。很简单,谢谢。
【解决方案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 ""

【讨论】:

  • 这是我试图描述的一个非常清楚的例子。谢谢你。对我很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 2020-05-29
  • 2017-03-12
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多