【问题标题】:python use result of function to decide if function result should be usedpython使用函数结果来决定是否应该使用函数结果
【发布时间】:2017-04-17 11:20:53
【问题描述】:

您通常希望使用None 作为函数的返回值。如果函数返回None 并且如果不使用函数的结果,则如果您想做一件事,是否有避免调用函数两次的 Python 习惯用法。下面是一个愚蠢的例子。

def foo(a, b):
  if b == 0:
    return(None)
  else:
    return(a/b)


a = b = 2
if foo(a, b) is None: #Do one thing. 1st call to function.
  print('b cannot be null')
else: #Use the result of function. 2nd function call.
  print('The result is: ' + str(foo(a,b)) )

这种有状态的方式是另一种选择吗(只有一个函数调用,但需要将可能很大的结果分配给变量)?:

res = foo(a, b)
if res is not None: 
  print('The result is: ' + str(res) )
else:
  print('b cannot be null')

【问题讨论】:

  • 您为什么不直接在 foo 中执行您需要的操作?如果您打印 b 或在 foo.h 中打印结果。结果在函数 foo 的范围和上下文中。
  • 是的——这是一个很好的建议(——也许很明显,但是,嘿,我想在这里学习)
  • 结果是否巨大并不重要,将其分配给变量并不是一项昂贵的操作。但另一种方法可能是抛出异常而不是返回None
  • 我明白了 - 因为异常不会停止/破坏程序?

标签: python function if-statement


【解决方案1】:

在您的示例中, foo 返回 None 表示:“参数中的某些内容错误,我无法返回有效值”。 在这种情况下,使用异常会更清楚:

def foo(a, b):
    if b == 0:
        raise ValueError("b can't be zero")
    else:
        return a/b

因此,如果 b 为 null,则 foo 不会返回任何内容 - 您不必测试返回值来检查它是否有效,或者它是否意味着“发生了错误”。如果 foo 返回一些东西,你就确定它是一个有效的结果。

现在,要使用 foo,您可以使用 try ... except 块:

a = 2
b = 0

try:
    print('The result is: ' + str(foo(a,b)) )
except ValueError as msg:
    print(msg)

# b can't be zero

如果您不在这样的块中调用foo,您的程序将停止并显示一个很好的、信息丰富的错误消息:

foo(a, b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-89e9686ab4be> in <module>()
     14     print(msg)
     15 
---> 16 foo(a, b)

<ipython-input-36-89e9686ab4be> in foo(a, b)
      1 def foo(a, b):
      2     if b == 0:
----> 3         raise ValueError("b can't be zero")
      4     else:
      5         return a/b

ValueError: b can't be zero

这也很好,因为当出现问题时,您的程序应该立即失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2013-11-03
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多