- 普通参数
1 #普通参数 2 def sum(x, y, z): 3 ''' 4 :param args: 5 :return: 6 ''' 7 print(x) 8 print(y) 9 print(z) 10 # sum(1,2) #报错 11 # sum(1, 2, 3, 5) #报错 12 # sum(1, 2, 3) #位置参数必须与形参一一对应 13 # sum(y = 2, x = 1, z = 5) #关键字参数不需要与形参一一对应 14 # sum(1, 2, z = 6) #两种参数混用时,位置参数必须要在关键字参数的左侧
- 默认参数
1 #默认参数 2 def test(x, type = 'world'): #type = 'world'是默认参数 3 print(x) 4 print(type) 5 test(3) #第二个参数若不传就是默认参数 6 # test(4, 'hello')
- 动态参数
1 #动态参数:*列表 **字典 2 def test1(x, *args): #只能用于位置参数 3 print(x) 4 print(args) 5 test1(5, 5, 2, 3) # 5, 2, 3传给args作为元组参数 6 #5 7 # (5, 2, 3) 8 9 test1(5, [2,3,6]) #[5, 3, 6]作为一个整体传给args作为元组中的第一个参数 10 # 5 11 # ([2, 3, 6],) 12 13 test1(5, *[2,3,6]) #遍历[5, 3, 6]作为agrs元组的元素 14 # 5 15 # (2, 3, 6) 16 17 test1(5, *(2,3,6)) #遍历(5, 3, 6)作为agrs元组的元素 18 # # 5 19 # # (2, 3, 6) 20 21 test1(5, **{'name': 'chen'}) #遍历(5, 3, 6)作为agrs元组的元素 22 # # 5 23 # # (2, 3, 6) 24 25 def test2(x, **kwargs): #可用于位置参数与关键字参数 26 print(x) 27 print(kwargs) 28 test2(1, y = 3, z = 5) 29 # 1 30 # {'y': 3, 'z': 5} 31 32 test2(6, **{'y' : 5, 'z' : 9}) 33 # 6 34 # {'y': 5, 'z': 9}