在函数中同时返回布尔值和变量?蟒蛇

时间:2015-08-06 14:52:44

标签: python python-2.7 pass-by-reference

是否可以从python

中的函数返回布尔值和变量
def foo(self, x):
    if x > 5:
       y = 2  #for workaround with pass by reference method 
       return true , y

# calling it by
i = 0
for i in range (0,10): 
    if foo(i):
        ref_value = y  #to get the reference value 

2 个答案:

答案 0 :(得分:3)

是的,上面的代码返回tuple,你可以返回多个这样的值(在元组或列表中等),但是你必须接受它们( unpack )所有在调用方面(要么全部接受,要么接受元组/列表作为单个元素)。示例/演示 -

>>> def foo(i):
...     if i > 5:
...             y = 2
...             return True, y
...     return False,0
...
>>> for i in range(0,10):
...     x,y = foo(i)
...     if x:
...             ret_value = y
...     else:
...             ret_value = 0
...     print(ret_value)
...
0
0
0
0
0
0
2
2
2
2
>>> type(foo(6))        #Example to show type of value returned.
<class 'tuple'>

答案 1 :(得分:1)

是的,您需要从返回的结果中解压缩两个值:

i = 0
for i in range (0,10):
    cond, y = foo(i) 
    if cond:
        ref_value = y