[英]Can I hide some of my function's return values when I use it inside another function in Python?
I have a K function that returns three values (a,b and c) and I am using it in multiple places in my programme. 我有一个返回三个值(a,b和c)的K函数,并且在程序中的多个地方都在使用它。 I also want to use this function inside an H function.
我也想在H函数中使用此函数。 However, when I use it inside H function, I want it to return only its first two return values (a and b), just like in the code below.
但是,当我在H函数中使用它时,我希望它仅返回其前两个返回值(a和b),就像下面的代码一样。 Is there a way with which I can hide the c when I use K inside H?
当我在H中使用K时,是否可以隐藏c? Or should I just redefine K function inside H function separately in such a way that it returns only a and b values?
还是应该只在H函数中重新定义K函数,使其仅返回a和b值?
def K(x):
...
return a,b,c
def H(y):
...
a,b=K(y)
...
return p
Thanks! 谢谢!
You can use underscore '_' 您可以使用下划线“ _”
def foo():
return 3,4,5
x,_,_ = foo()
print(x)
output 产量
3 3
If the values you are returning are the first ones (eg only a, or only a and b), then your code will work as is. 如果您返回的值是第一个值(例如,仅a,或仅a和b),那么您的代码将按原样工作。
If the values you are returning aren't the first ones (eg only b, or a and c), you'd need to use something like a, _, c = K(y)
(the _
is the common sign of a "dummy" variable). 如果您返回的值不是第一个(例如,只有b或a和c),则需要使用
a, _, c = K(y)
( _
是a的公称“虚拟变量)。
You can also add a type check in the Function K: 您还可以在功能K中添加类型检查:
def K(x, return_only_ab=False): # add default parameter return_only_ab
...
if not return_only_ab: # if False then return all the three variables
return a,b,c
else: # else reutrn only a, b that you need
return a, b
def H(y):
...
a,b=K(y, return_only_ab=True) # here you ll only get a,b and then do something with it
...
return p
hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.