这篇主要探讨 ** 和 * 前缀运算符,**在变量之前使用的*and **运算符.
一个星(*):表示接收的参数作为元组来处理
两个星(**):表示接收的参数作为字典来处理
简单示例:
>>> numbers = [2, 1, 3, 4, 7] >>> more_numbers = [*numbers, 11, 18] >>> print(*more_numbers, sep=', ') 2, 1, 3, 4, 7, 11, 18
用途:
- 使用 * 和 ** 将参数传递给函数
- 使用**和**捕获传递给函数的参数
- 使用*只接受关键字参数
- 使用*元组拆包过程中捕获项目
- 使用*解包iterables到一个列表/元组
- 使用**要解压缩词典到其他字典
例子解释:
1.调用函数时,*可以使用运算符将可迭代对象解压缩为函数调用中的参数:
>>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> print(fruits[0], fruits[1], fruits[2], fruits[3]) lemon pear watermelon tomato >>> print(*fruits) lemon pear watermelon tomato
该print(*fruits)行将fruits列表中的所有项目print作为单独的参数传递到函数调用中,而我们甚至不需要知道列表中有多少个参数。
2.** 运算符允许我们采取键值对的字典,并把它解压到函数调用中的关键字参数。
>>> date_info = {'year': "2020", 'month': "01", 'day': "01"} >>> filename = "{year}-{month}-{day}.txt".format(**date_info) >>> filename '2020-01-01.txt'
** 将关键字参数解包到函数调用中并不是很常见。我最常看到的地方是练习继承时:super()通常要同时包含*和**。
双方*并 **可以在函数调用中多次使用,像Python 3.5的。
>> fruits = ['lemon', 'pear', 'watermelon', 'tomato'] >>> numbers = [2, 1, 3, 4, 7] >>> print(*numbers, *fruits) 2 1 3 4 7 lemon pear watermelon tomato **多次使用类似: >>> date_info = {'year': "2020", 'month': "01", 'day': "01"} >>> track_info = {'artist': "Beethoven", 'title': 'Symphony No 5'} >>> filename = "{year}-{month}-{day}-{artist}-{title}.txt".format( ... **date_info, ... **track_info, ... ) >>> filename '2020-01-01-Beethoven-Symphony No 5.txt'
3.定义函数时,*可以使用运算符捕获为函数提供的无限数量的位置参数。这些参数被捕获到一个元组中。
from random import randint def roll(*dice): return sum(randint(1, die) for die in dice
4.我们可以用**定义一个函数时,捕捉给予功能到字典中的任何关键字参数:
def tag(tag_name, **attributes): attribute_list = [ f'{name}="{value}"' for name, value in attributes.items() ] return f"<{tag_name} {' '.join(attribute_list)}>"
5.
本文来源gaodai.ma#com搞##代!^码7网
带有仅关键字参数的位置参数,要接受仅关键字的参数,可以*在定义函数时在使用后放置命名参数
def get_multiple(*keys, dictionary, default=None): return [ dictionary.get(key, default) for key in keys ] 上面的函数可以这样使用: >>> fruits = {'lemon': 'yellow', 'orange': 'orange', 'tomato': 'red'} >>> get_multiple('lemon', 'tomato', 'squash', dictionary=fruits, default='unknown') ['yellow', 'red', 'unknown']
参数dictionaryand default在其后*keys,这意味着只能将它们指定为关键字参数。如果我们尝试在位置上指定它们,则会收到错误消息:
>>> fruits = {'lemon': 'yellow', 'orange': 'orange', 'tomato': 'red'} >>> get_multiple('lemon', 'tomato', 'squash', fruits, 'unknown') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: get_multiple() missing 1 required keyword-only argument: 'dictionary'