Python基础知识:如何检查函数是否返回多个值?

Jur*_*ocs 0 python

我知道的基本内容...... ;-P但是检查函数是否返回某些值的最佳方法是什么?

def hillupillu():
    a= None
    b="lillestalle"
    return a,b

if i and j in hillupillu(): #how can i check if i or j are empty? this is not doing it of course;-P
    print i,j 
Run Code Online (Sandbox Code Playgroud)

Fre*_*Foo 8

如果你的意思是你无法预测某些函数的返回值的数量,那么

i, j = hillupillu()
Run Code Online (Sandbox Code Playgroud)

ValueError如果函数没有返回两个值,则会引发a .您可以使用通常的try构造来捕获它:

try:
    i, j = hillupillu()
except ValueError:
    print("Hey, I was expecting two values!")
Run Code Online (Sandbox Code Playgroud)

这遵循了"请求宽恕而非许可"的常见Python习语.如果hillupillu可以提升ValueError自己,你会想要做一个明确的检查:

r = hillupillu()
if len(r) != 2:  # maybe check whether it's a tuple as well with isinstance(r, tuple)
    print("Hey, I was expecting two values!")
i, j = r
Run Code Online (Sandbox Code Playgroud)

如果您想要None在返回的值中检查,请None in (i, j)if-clause中检查.

  • @Jurudocs:然而,经验丰富的Pythonistas会告诉你"请求宽恕比允许更容易"; 如果你有选项,那么让程序抛出异常并处理它而不是编写你自己的检查. (2认同)

jfs*_*jfs 7

Python中的函数始终返回单个值.特别是他们可以返回一个元组.

如果你不知道元组中有多少值,你可以检查它的长度:

tuple_ = hillupillu()
i = tuple_[0] if tuple_ else None
j = tuple_[1] if len(tuple_) > 1 else None
Run Code Online (Sandbox Code Playgroud)