您想编写一个接受任意数量输入参数的函数。
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中。