五、函数_3.关键字参数和关键字收集参数

关键字参数

通常定义在收集参数后面
需要通过形参的名称来传递实参

def event(a,b,*gather,substitution,c='run') :
    print(a,b,c)
    print(gather)
    print(substitution)

event('football','swimming','fitness',c='running',substitution='hike')

def event(age,name) :
    print(age,name)

event(name='Co',age=20)

football swimming running
('fitness',)
hike
20 Co

关键字收集参数

接收额外的关键字参数,并把它们放入一个dict中
用“ ** ”加参数名定义,**参数名

def event(a,b,c='run',*gather,time,number,**kwargs) :
    print(a,b,c)
    print(gather)
    print(time,number)
    print(kwargs)

event('football','swimming','run','fitness','hike',time='10.30',number=5,place='A',duration=60)

# event(a=1,b=2,c=3,'fitness',time=30,number=5,place='A')    # 这是错误的方式
# 当形参中同时有收集参数和关键字参数时,关键字参数的传递必须在收集参数后面,此时普通参数不能用关键字参数传递实参

football swimming run
('fitness', 'hike')
10.30 5
{'place': 'A', 'duration': 60}
上一篇:【优化求解】基于蝙蝠算法求解最优目标matlab源码


下一篇:麻雀搜索算法SSA(有matlab代码,复制粘贴即可)