使用条件返回时,如果尝试从函数返回多个值,则函数相对于实际返回值的行为不稳定。
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return z, w if diagnostic else w
print(test_function(3,4)) # output tuple ([],12)
# lets switch order of the return from z,w to w,z
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return w,z if diagnostic else w
print(test_function(3,4)) # output tuple (12,12)
# lets try retun the diagnostic value itself to see what function things is happening
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return diagnostic if diagnostic else w
print(test_function(3,4)) # returns 12, so diagnostic is retuning false
# rewrite conditional to "if not"
def test_function(x,y, diagnostic:bool=False):
w = x*y
z = []
if diagnostic:
z = [w,w*2]
return w if not diagnostic else w,z
print(test_function(3,4)) # returns (12, [])
2条答案
按热度按时间sg24os4d1#
问题在于运算符优先级:
,
优先级低于... if ... else ...
,所以你实际上写的是return z, (w if diagnostic else w)
,或者在第二个函数中return w, (z if diagnostic else w)
.这方面的暗示是
diagnostic
是False
但您仍然返回一对值。对于你想要的行为,你应该写
return (z, w) if diagnostic else w
. 注意,这里的括号不需要使它成为一个元组-无论哪种方式,它都是一个元组-括号用于指定优先级。sdnqo3pr2#
如果在条件返回中返回多个值,由于运算符优先级,这些值必须以元组形式显式返回: