- 关键字参数
def func(name='zhangsan', age=18): print("我的名字是{0},今年{1}岁".format(name,age)) func() #姓名、年龄均为默认值zhansan和18 func(age=20) #姓名为默认值zhangsan,年龄为20 func(name='lisi',age=28) #姓名和年龄分别为lisi和28
- 收集参数
def func(*args):#定义形式参数args,以*开头,表示参数收集,可以接受任意多个参数,都打包装入元组args中,可以传空 for item in args: #遍历元组args print(item) func(1,2,3,'zhangsan','lisi',4,5) func(‘huawei’,'xiaomi','sanxing')
- 关键字收集参数
def student(**kwargs): #以**开头的参数表示为关键字收集参数,可以传空 print(type(kwargs)) #关键字参数的类型为字典(即key,value对) for k,v in kwargs.items(): #遍历字典 print(k,"...",v) student(name='zhangsan', age=19, addr='peking', worker='teacher') student(name='lisi', age=22)
- 普通参数、收集参数、关键字参数的调研顺序
def stu(name, age, *args, hobby='none',**kwargs): #注意顺序为依次:普通参数、收集参数、关键字参数、关键字收集参数 print("my name is {0}, i'm {1} years old".format(name,age)) if hobby=='none': print("sorry, i've no hobbies") else: print("my hobby is {0}".format(hobby)) print("*"*20) for item in args: print(item) print("#"*20) for k,v in kwargs.items(): print(k,"...",v) name="zhangsan" age=19 stu(name, age) #只传入普通参数 stu(name, age, hobby="swim") #传入普通参数、关键字参数 stu(name, age, "lisi", "wangwu", hobby="swim", hobby1="cook", hobby2="basketball") #传入普通参数、收集参数、关键字参数、关键字手机参数,注意顺序!
输出为
my name is zhangsan, i'm 19 years old sorry, i've no hobbies ******************** #################### my name is zhangsan, i'm 19 years old my hobby is: swim ******************** #################### my name is zhangsan, i'm 19 years old my hobby is: swim ******************** lisi wangwu #################### hobby1 ... cook hobby2 ... basketball
- 收集参数、关键字收集参数的解包
def func(*args): n = 0 for item in args: print("loop {0}".format(n)) print(item) n += 1 l = [1,2,3,'zhangsan','lisi',4,5] func(l) #未解包,此时for循环进循环依次,且打印的item直接为整个数组 func(*l) #加上*进行解包,for循环遍历数组中的每个元素
同理,对关键字收集参数也可以进行解包,使用两个*号:**