是否可以从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
答案 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