如何編寫接受任意數量引數的 Python 函式
問題
你要編寫一個能接受任意數量輸入引數的函式。
解決方案
Python 中的 * 引數可接受任意數量的引數。我們來看一個求取任意兩個或更多個數字的平均值的例子就能理解這個概念。在下例中,rest_arg 是一個包含所有附加引數(本例中為數字)的元組。此函式在執行平均值計算時,將這些引數視為序列。
# Sample function to find the average of the given numbers
def define_average(first_arg, *rest_arg):
average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg))
print(f"Output \n *** The average for the given numbers {average}")
# Call the function with two numbers
define_average(1, 2)輸出
*** The average for the given numbers 1.5
# Call the function with more numbers define_average(1, 2, 3, 4)
輸出
*** The average for the given numbers 2.5
要接受任意數量的關鍵字引數,請使用以 ** 開頭的引數。
def player_stats(player_name, player_country, **player_titles):
print(f"Output \n*** Type of player_titles - {type(player_titles)}")
titles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items())
print(f"*** Type of titles post conversion - {type(titles)}")
stats = 'The player - {name} from {country} has {titles}'.format(name = player_name,
country=player_country,
titles=titles)
return stats
player_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103)輸出
*** Type of player_titles - <class 'dict'> *** Type of titles post conversion - <class 'str'>
'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103'
在上例中,player_titles 為一個包含傳遞過來的關鍵字引數的字典。
如果你想編寫一個可以同時接收任意數量的位置引數和關鍵字專用引數的函式,請同時使用 * 和 **。
def func_anyargs(*args, **kwargs): print(args) # A tuple print(kwargs) # A dict
透過使用此函式,所有位置引數都將放入元組 args 中的所有關鍵字引數都將放入字典 kwargs 中。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP