[英]Can I use a variable from a function that's inside of another class?
[英]Can I hide some of my function's return values when I use it inside another function in Python?
我有一個返回三個值(a,b和c)的K函數,並且在程序中的多個地方都在使用它。 我也想在H函數中使用此函數。 但是,當我在H函數中使用它時,我希望它僅返回其前兩個返回值(a和b),就像下面的代碼一樣。 當我在H中使用K時,是否可以隱藏c? 還是應該只在H函數中重新定義K函數,使其僅返回a和b值?
def K(x):
...
return a,b,c
def H(y):
...
a,b=K(y)
...
return p
謝謝!
您可以使用下划線“ _”
def foo():
return 3,4,5
x,_,_ = foo()
print(x)
產量
3
如果您返回的值是第一個值(例如,僅a,或僅a和b),那么您的代碼將按原樣工作。
如果您返回的值不是第一個(例如,只有b或a和c),則需要使用a, _, c = K(y)
( _
是a的公稱“虛擬變量)。
您還可以在功能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
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.