2016-01-20 84 views
4

我發現了許多關於python函數參數的查詢,但仍然感到困惑。假設我想在某些函數中傳遞幾個參數。如何在python中傳遞默認和可變長度參數?

def anyFunc(name, age, sex = 'M', *cap_letters): 
    print "name ", name 
    print "age ", age 
    print "sex ", sex 
    for s in cap_letters: 
     print "capital letter: ", s 

name &年齡參數是位置參數。性別是默認參數,其次是非關鍵字參數的可變長度,這是非常少的隨機資本字母。所以,現在,如果我跑

anyFunc("Mona", 45, 'F', *('H', 'K', 'L')) 

它給我完美的輸出..

name Mona 
age 45 
sex F 
capital letter: H 
capital letter: K 
capital letter: L 

但是,如果我通過下面,我想使用默認性值,而不是傳遞的參數。產出不如預期的。

anyFunc("John", 45, *('H', 'K', 'L')) 

name John 
age 45 
sex H 
capital letter: K 
capital letter: L 

它應該採用性別的默認值即'M'。我也嘗試在最後通過性別論證,但它給了我語法錯誤。有什麼方法可以實現我想要的嗎?

+0

我的Python 3.0≥,你可以做'sex'一個[關鍵詞 - ** **僅參數(https://www.python.org/dev/ PEPS/PEP-3102 /)。但是,在Python 2.x中,您沒有該選項。 –

回答

0

在你的功能中做一個** kwargs。在你的函數內部,檢查用戶是否已經通過性別作爲關鍵參數。如果用戶沒有通過任何比繼續默認性別的任何東西。

你的函數看起來就像這樣:

def anyFunc(name, age, *cap_letters,**sexKwarg): print "name ", name print "age ", age sex = sexKwarg.get('sex', 'M') print "sex ", sex for s in cap_letters: print "capital letter: ", s 用法: anyFunc("Mona", 45, *('H', 'K', 'L'), sex = 'F') anyFunc("Mona", 45, *('H', 'K', 'L')) ##use default sex

+0

是的..我必須通過這種方式..謝謝你的回覆.. – Ankur

+0

我已經更新了我的答案,併發布了一個完整的解決方案。接受我的答案,如果這有幫助 –

+2

'kwargs'是一個字典,所以迭代通過它來得到一個密鑰的值是瘋了。只要做'sex = kwargs.get('sex','M')'。 – BlackJack

1

不要使用*神奇的功能,簽名,如果您還使用/需要它把呼叫一側。然後,只需將其放在兩側,不要使問題更加複雜,因爲它必須是:

def any_func(name, age, sex='M', capital_letters=()): 
    print 'name ', name 
    print 'age ', age 
    print 'sex ', sex 
    for capital_letter in capital_letters: 
     print 'capital letter: ', capital_letter 

古稱:

any_func('Mona', 45, 'F', ('H', 'K', 'L')) 

以默認sex

any_func('John', 45, capital_letters=('H', 'K', 'L')) 

如果您不喜歡在很多調用中拼寫出參數名稱,並且可以對參數重新排序,則交換最後兩個參數:

def any_func(name, age, capital_letters=(), sex='M'): 
    print 'name ', name 
    print 'age ', age 
    print 'sex ', sex 
    for capital_letter in capital_letters: 
     print 'capital letter: ', capital_letter 

電話:

any_func('Mona', 45, ('H', 'K', 'L'), 'F') 
any_func('John', 45, ('H', 'K', 'L')) 
相關問題