# *args
def eat(*args): # 将实参角度:所有的位置参数聚合到一个元组中;定义一个函数的时候,*代表聚合
print(args) # ('奶茶', '烤鸭', '火锅', '烤鱼')
print(f'我请你吃:{args}') # 我请你吃:('奶茶', '烤鸭', '火锅', '烤鱼')
eat('奶茶', '烤鸭', '火锅', '烤鱼')
# **kwargs
def func1(**kwargs): # 函数定义的时: **将实参角度的所有关键字参数聚合成了一个字典,并给了kwargs
print(kwargs) # {'name': 'hello', 'age': 17, 'edu': '博士'}
func1(name='hello', age=17, edu='博士')
# 万能参数(动态参数):*agrs , **kwargs
def func2(*args, **kwargs):
print(args) # ('hello', 20, 'goto')
print(kwargs) # {'name': 'world', 'age': 17}
func2('hello', 20, 'goto', name='world', age=17)
# * 的魔性用法
def func3(*args, **kwargs):
print(args) # ([11, 22, 55, 66, 99], ['today', 'yesterday', 'hello world'])
print(kwargs) # {}
l1 = [11,22,55,66,99]
l2 = ['today', 'yesterday', 'hello world']
func3(l1, l2)
def func4(*args, **kwargs):
print(args) # (11, 22, 55, 66, 99, 'today', 'yesterday', 'hello world')
print(kwargs) # {}
l1 = [11,22,55,66,99]
l2 = ['today', 'yesterday', 'hello world']
func4(*l1, *l2) # 函数调用时,*iterable(可迭代对象) 代表打散。
def func5(*args, **kwargs):
print(args) # ({'name': 'hello', 'age': 10}, {'job': 'stu'})
print(kwargs) # {}
func5({'name':'hello', 'age':10}, {'job': 'stu'})
def func5(*args, **kwargs):
print(args) # ()
print(kwargs) # {'name': 'hello', 'age': 10, 'job': 'stu'}
func5(**{'name':'hello', 'age':10}, **{'job': 'stu'}) # 函数调用时,**dict 代表打散,此时字典的键不能是数字。
# * 在函数之外的用法:处理剩余元素
a, b, *c = 1,2,3,6,9,99,10
print(a, b, c) # 1 2 [3, 6, 9, 99, 10]
a, *c, b = 1,2,3,6,9,99,10
print(a, c, b) # 1 [2, 3, 6, 9, 99] 10
q, *w = range(1,10)
print(q,w) # 1 [2, 3, 4, 5, 6, 7, 8, 9]
# 形参角度参数的顺序:位置参数,*args, 默认参数, **kwargs
def func(a, b, *args, sex='男', **kwargs):
print(a) # 1
print(b) # 22
print(args) # (56, 85, 41, 23)
print(sex) # 男
print(kwargs) # {'name': 'hello', 'job': 'it'}
func(1,22,56,85,41,23,name='hello',job='it')
# 形参角度:仅限关键字参数(函数调用时只能通过关键字传参),位于*args与**kwargs之间
def func(a, b, *args, sex='男', age, **kwargs):
print(a) # 1
print(b) # 22
print(args) # (56, 85, 41, 23)
print(sex) # 男
print(age) # 77
print(kwargs) # {'name': 'hello', 'job': 'it'}
func(1,22,56,85,41,23,age=77,name='hello',job='it')
Python万能参数
于 2022-02-13 11:43:50 首次发布