其他分享
首页 > 其他分享> > 五、函数_3.关键字参数和关键字收集参数

五、函数_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}

标签:收集,number,关键字,参数,fitness,print,event
来源: https://www.cnblogs.com/HyeJeong/p/15468723.html