仅从函数访问返回值之一

时间:2019-05-04 15:56:33

标签: python python-3.x function

如何仅访问以下值之一:

我的代码:

def test():
    a = 4
    b = 5
    c = 6

    return a, b, c 

a = test().a  # only want "a" from the function

4 个答案:

答案 0 :(得分:2)

您可以使用占位符_

来忽略其他值
def test():
    a = 4
    b = 5
    c = 6

    return a, b,  c

#Ignore b and c
a, _, _ = test()
print(a)
#4

或者您可以返回值字典并从字典中访问a

def test():
    a = 4
    b = 5
    c = 6

    return locals()

print(test()['a'])
#4

或者您可以使用索引找到返回的元组的第一个元素,前提是您知道a是第一个元素,如上面的Tim's Answer所述

def test():
    a = 4
    b = 5
    c = 6

    return a, b, c

print(test()[0])
#a

答案 1 :(得分:1)

函数test()返回一个tuple,因此,要访问a,您必须使用以下代码:

a = test()[0]

答案 2 :(得分:0)

您可以改为返回字典:

def test():
    a = 4
    b = 5
    c = 6

    return {"a":a, "b":b, "c":c}

print(test()["a"])

4

如果要坚持使用当前的方法,那么您可能能够做的最好的事情就是只打印返回的元组中的第一个元素:

print(test()[0])

但这当然意味着调用者必须知道a恰好与第一个值一致。

答案 3 :(得分:0)

有几种方法可以做到这一点。

a, b, c = test() # ignore b and c

a, *_ = test() # ignore _ which captures b and c

a = test()[0]

a = test()
a[0] # which is equal to the 'a' inside the test function.