Python函數的參數

來源:互聯網
上載者:User

標籤:限制   一點   require   back   module   name   while   ror   位置   

位置參數:

比如:

>>> def power(x, n):    s = 1    while n > 0:        n = n - 1        s = s * x    return s

其中x和n分別佔了一個位置,所以稱為位置參數,

位置參數是必須傳進來的!

預設參數:

比如:

>>> def power(x, n=2):    s = 1    while n > 0:        n = n - 1        s = s * x    return s

必選參數在前,預設參數在後,當不傳入預設參數時,

函數會預設為指定的值。傳入預設參數時,會修改為

傳入的值。定義預設參數要牢記一點:預設參數必須指向不變對象!

可變參數:
>>> def my_sum(*numbers):    sum = 0    for n in numbers:        sum = sum + n    return sum

調用該函數時,可以傳入任意個參數,包括0個參數

Python允許你在list或tuple前面加一個*號,變成可變

參數傳進去。

關鍵字參數:
>>> def person(name, sex, **kw):    print(‘name:‘, name, ‘sex‘, sex, ‘other:‘, kw)

關鍵字參數允許你傳入0個或任意個含參數名的參數

調用該函數時,可以只傳入必選參數,

也可以傳入任意個數的關鍵字參數。

也可以先組裝出一個dict,在前面加**,

傳進去。

命名關鍵字參數:
>>> def person(name, age, *, city, sex):    print(name, age, city, sex)

要限制關鍵字參數的名字,就可以用命名關鍵字參數

命名關鍵字參數需要一個特殊分隔字元*

若已經有了一個可變參數,就不再需要一個特殊分隔字元*

>>> def person(name, age, *args, city, sex):    print(name, age, args, city, sex)

命名關鍵字參數必須傳入參數名

指定的命名關鍵字參數也必須傳入:

>>> person(‘a‘,12,1212,212,1212,city=‘aaa‘)Traceback (most recent call last):  File "<pyshell#365>", line 1, in <module>    person(‘a‘,12,1212,212,1212,city=‘aaa‘)TypeError: person() missing 1 required keyword-only argument: ‘job‘

當命名關鍵字參數有預設值時,可以不傳入該參數

如果沒有可變參數,就必須在命名關鍵字參數前

有*號,否則無法分辨命名關鍵字參數與位置參數

參數定義的順序必須是:必選參數、預設參數、可變參數、命名關鍵字參數和關鍵字參數

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.