python中函數接收多餘參數

來源:互聯網
上載者:User

標籤:

代碼:

def fun(x):    return x    print fun(10)

函數fun(x)接受參數是x,傳入數字"10",列印函數的傳回值結果 就是10,如果我傳遞多個參數時,程式就會出錯,如:

def fun(x):    return xprint(fun(10,20))
Traceback (most recent call last):  File "aa.py", line 7, in <module>    print(fun(10,20))TypeError: fun() takes exactly 1 argument (2 given)

給出的結果是:給了2個參數。為瞭解決這個問題,引入*args把多餘的參數放入到元組中,如:

def fun(x, *args):    print args    return x    print(fun(10,20))

這樣的話,x只接受第一個參數,其他的都存放到args這個元組中去,結果如:

(20,)10

元組裡面是不能存放字典類型的資料,如果我存放字典類型資料是否會報錯?看:

def fun(x, *args):    print args    return x    print(fun(10,20,y=2))
Traceback (most recent call last):  File "aa.py", line 8, in <module>    print(fun(10,20,y=2))TypeError: fun() got an unexpected keyword argument ‘y‘

此時,給出報錯:捕捉到一個未知的關鍵字參數 y,為瞭解決這個我們需要引入 **kw來解決傳入參數是字典類型的資料,看:

def fun(x, *args, **kw):    print kw    print args    return x    print(fun(10,20,y=2))

運行結果如:

{‘y‘:20}(20,10

看下整個效果:

def fun(x, *args, **kw):    print kw    print args    return x    print(fun(10,20,40,50.5,y=2,z=3,f=5.5))

運行結果:

{‘y‘: 2, ‘z‘: 3, ‘f‘: 5.5}(20, 40, 50.5)10

 

主要注意的地方是:fun(x, *args, **kw) 在調用函數時,傳入字典參數是不可以傳入 x = * 這種類型,會出現錯誤,如:

Traceback (most recent call last):  File "aa.py", line 9, in <module>    print(fun(10,20,40,50.5,z=3,x=2,y=5.5))TypeError: fun() got multiple values for keyword argument ‘x‘
  File "aa.py", line 9    print(fun(x=2,10,20,40,50.5,z=3,y=5.5))SyntaxError: non-keyword arg after keyword arg

 

python中函數接收多餘參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.