[英]Way to pass multiple parameters to a function in python
我編寫了一個調用函數的python腳本。 此函數將7個列表作為函數內的參數,如下所示:
def WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse,
AlldaysHLFound_bse, AllvolumeFound_bse,
AllprevCloseFound_bse, AllchangePercentFound_bse,
AllmarketCapFound_bse):
其中除link
之外的所有參數都是列表。 但這使得我的代碼看起來很丑陋。 我將這些列表傳遞給此函數,因為該函數在所有這些列表中附加了幾個值。 如何以更易讀的方式為其他用戶執行此操作?
測試功能:
您可以使用多個參數來表示*args
和多個關鍵字,這些關鍵字由**kwargs
表示並傳遞給函數:
def test(*args, **kwargs):
print('arguments are:')
for i in args:
print(i)
print('\nkeywords are:')
for j in kwargs:
print(j)
例:
然后使用任何類型的數據作為參數,並使用與函數關鍵字一樣多的參數。 該函數將自動檢測它們並將它們分離為參數和關鍵字:
a1 = "Bob" #string
a2 = [1,2,3] #list
a3 = {'a': 222, #dictionary
'b': 333,
'c': 444}
test(a1, a2, a3, param1=True, param2=12, param3=None)
輸出:
arguments are:
Bob
[1, 2, 3]
{'a': 222, 'c': 444, 'b': 333}
keywords are:
param3
param2
param1
您可以將其更改為:
def WorkDetails(link, details):
然后將其調用為:
details = [ AllcurrValFound_bse, AllyearlyHLFound_bse,
AlldaysHLFound_bse, AllvolumeFound_bse,
AllprevCloseFound_bse, AllchangePercentFound_bse,
AllmarketCapFound_bse ]
workDetails(link, details)
您可以通過以下方式獲得不同的價值:
AllcurrValFound_bse = details[0]
AllyearlyHLFound_bse = details[1]
...
將details
轉換為字典會更加健壯,將變量名稱作為鍵,因此請在幾行代碼與防御性編程之間選擇= p
如果您不需要為列表使用名稱,則可以使用*args
:
def WorkDetails(link, *args):
if args[0] == ... # Same as if AllcurrValFound_bse == ...
...
# Call the function:
WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, AlldaysHLFound_bse, AllvolumeFound_bse, AllprevCloseFound_bse, AllchangePercentFound_bse, AllmarketCapFound_bs)
或者你可以使用字典
def WorkDetails(link, dict_of_lists):
if dict_of_lists["AllcurrValFound_bse"] == ...
...
# Call the function
myLists = {
"AllcurrValFound_bse": AllcurrValFound_bse,
"AllyearlyHLFound_bse": AllyearlyHLFound_bse,
...,
...
}
WorkDetails(link, myLists)
我認為** kwarg的用法更好。 看這個例子:
def MyFunc(**kwargs):
print kwargs
MyFunc(par1=[1],par2=[2],par3=[1,2,3])
通常,不建議將超過3個參數傳遞給函數。 這不是python特有的,而是一般的軟件設計。 您可以在此處閱讀有關如何減少傳遞給函數的參數數量的更多信息。
按照以前的答案的觀點,但從更一般的角度來看,我想補充一點,有幾種方法可以使您的代碼更具可讀性:
link
的函數, specific_list
, list_type
。通過執行此操作,您可以在WorkDetails
函數中檢測使用list_type
傳遞的列表,並將正確的元素添加到該specific list
) 希望這有幫助。
您需要傳遞那么多列表,這表明您的函數不是只做一件事,您應該通過將其分解為更小的函數和/或將其轉換為類來重構它。 您可以將參數作為關鍵字傳遞,或者將任意數量的參數傳遞給函數, 如此StackOverflow頁面所述 ,但如果您的函數執行多項操作,則其他人仍然難以閱讀和理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.