python函数条件返回

nkcskrwz  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(245)

使用条件返回时,如果尝试从函数返回多个值,则函数相对于实际返回值的行为不稳定。

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, [])
sg24os4d

sg24os4d1#

问题在于运算符优先级: , 优先级低于 ... if ... else ... ,所以你实际上写的是 return z, (w if diagnostic else w) ,或者在第二个函数中 return w, (z if diagnostic else w) .
这方面的暗示是 diagnosticFalse 但您仍然返回一对值。
对于你想要的行为,你应该写 return (z, w) if diagnostic else w . 注意,这里的括号不需要使它成为一个元组-无论哪种方式,它都是一个元组-括号用于指定优先级。

sdnqo3pr

sdnqo3pr2#

如果在条件返回中返回多个值,由于运算符优先级,这些值必须以元组形式显式返回:

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)) # returns 12
print(test_function(3,4, diagnostic=False)) # returns (12, [12, 24])
w, z = test_function(3,4, diagnostic=True)
print(w) # returns 12
print(z) # returns [12,24]

相关问题