python中函數傳參詳解,python函數參詳解

來源:互聯網
上載者:User

python中函數傳參詳解,python函數參詳解

一、參數傳入規則

可變參數允許傳入0個或任意個參數,在函數調用時自動組裝成一個tuple;

關鍵字參數允許傳入0個或任意個參數,在函數調用時自動組裝成一個dict;

1. 傳入可變參數:

 def calc(*numbers):   sum = 0   for n in numbers:     sum = sum + n * n   return sum

以上定義函數,使用如下:

傳入多個參數,

calc(1, 2, 3, 4)30 #函數傳回值

傳入一個列表,

nums = [1, 2, 3]calc(*nums) # 通過 * 將list中的元素作為可變參數傳入函數14 # 函數傳回值

2.傳入關鍵字參數:

>>> def person(name, age, **kw):...   print('name: ', name, 'age: ', age, 'other: ', kw)... >>> >>> person('luhc', 24, city='Guangzhou')name: luhc age: 24 other: {'city': 'Guangzhou'}

同樣,可以將預先定義的dict作為參數傳入以上函數:

>>> info = {'city': 'Guangzhou', 'job': 'engineer'}>>> >>> person('luhc', 24, **info)name: luhc age: 24 other: {'city': 'Guangzhou', 'job': 'engineer'}

注意: 函數person 獲得的是參數 info 的一份拷貝,在函數內修改不會影響 info 的值

3. 在關鍵字參數中,可以限制關鍵字參數的名字:

# 通過 * 分割,以指定關鍵字參數名>>> def person(name, age, *, city, job):...   print('name: ', name, 'age: ', age, 'city: ', city, 'job: ', job)... >>> >>> person('luhc', 24, city='Guangzhou', job='engineer')name: luhc age: 24 city: Guangzhou job: engineer# 如果傳入參數中,存在參數名不在定義的範圍內,將拋出異常>>> person('luhc', 24, city='Guangzhou', jobs='engineer')Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: person() got an unexpected keyword argument 'jobs'>>>

此外,如果函數中已經指定可變參數,則 * 可以省略,如下:

# 省略了用 * 作為分割,指定關鍵字參數名>>> def person(name, age, *args, city, job):...   print('name: ', name, 'age: ', age, 'args: ', args, 'city: ', city, 'job: ', job)  ... >>> >>> person('luhc', 24, 'a', 'b', city='Guangz', job='engineer')name: luhc age: 24 args: ('a', 'b') city: Guangz job: engineer>>> # 同樣,如果傳入了關鍵字參數未指定的參數名,則拋出異常>>> person('luhc', 24, 'a', 'b', city='Guangz', job='engineer', test='a')Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: person() got an unexpected keyword argument 'test'>>>

二、參數組合使用:

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

def f1(a, b, c=0, *args, **kw):  print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)def f2(a, b, c=0, *, d, **kw):  print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

 以上就是本文給大家介紹的全部內容了,希望能夠對大家理解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.