7.1 可接受任意數(shù)量參數(shù)的函數(shù)

2018-02-24 15:26 更新

問題

你想構(gòu)造一個可接受任意數(shù)量參數(shù)的函數(shù)。

解決方案

為了能讓一個函數(shù)接受任意數(shù)量的位置參數(shù),可以使用一個*參數(shù)。例如:

def avg(first, *rest):
    return (first + sum(rest)) / (1 + len(rest))

# Sample use
avg(1, 2) # 1.5
avg(1, 2, 3, 4) # 2.5

在這個例子中,rest是由所有其他位置參數(shù)組成的元組。然后我們在代碼中把它當成了一個序列來進行后續(xù)的計算。

為了接受任意數(shù)量的關(guān)鍵字參數(shù),使用一個以**開頭的參數(shù)。比如:

import html

def make_element(name, value, **attrs):
    keyvals = [' %s="%s"' % item for item in attrs.items()]
    attr_str = ''.join(keyvals)
    element = '<{name}{attrs}>{value}</{name}>'.format(
                name=name,
                attrs=attr_str,
                value=html.escape(value))
    return element

# Example
# Creates '<item size="large" quantity="6">Albatross</item>'
make_element('item', 'Albatross', size='large', quantity=6)

# Creates '<p>&lt;spam&gt;</p>'
make_element('p', '<spam>')

在這里,attrs是一個包含所有被傳入進來的關(guān)鍵字參數(shù)的字典。

如果你還希望某個函數(shù)能同時接受任意數(shù)量的位置參數(shù)和關(guān)鍵字參數(shù),可以同時使用*和**。比如:

def anyargs(*args, **kwargs):
    print(args) # A tuple
    print(kwargs) # A dict

使用這個函數(shù)時,所有位置參數(shù)會被放到args元組中,所有關(guān)鍵字參數(shù)會被放到字典kwargs中。

討論

一個*參數(shù)只能出現(xiàn)在函數(shù)定義中最后一個位置參數(shù)后面,而 **參數(shù)只能出現(xiàn)在最后一個參數(shù)。有一點要注意的是,在*參數(shù)后面仍然可以定義其他參數(shù)。

def a(x, *args, y):
    pass

def b(x, *args, y, **kwargs):
    pass

這種參數(shù)就是我們所說的強制關(guān)鍵字參數(shù),在后面7.2小節(jié)還會詳細講解到。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號