1 def test(x,y,z): #这里xyz叫形参
2 print(x)
3 print(y)
4 print(z)
5
6 test(1,3,5) #这里135叫实参。这种方式叫位置参数
7 test(y=1,x=4,z=5) #关键字参数
8 test(1,3,z=6) #这种写法也可以,但是关键字必须要在位置参数之后,并且不能重复
1 def test1(x,z,y=2):
2 print(x)
3 print(y)
4 print(z)
5
6 test1(1,5)
7 test1(1,3)
8
9 #默认参数特点:调用函数的时候,默认参数非必需传递
10 #默认参数用途:软件安装时的默认选项,连接数据库时的默认端口
1 def test2(*args): # *args只能接收位置参数,不能接收关键词参数
2 print(args)
3
4 test2(1,2,3,6,8,9)
5 test2(*[2,4,6,2]) #args=tuple[2,4,6,2]
6
7 def test3(x,*args):
8 print(x)
9 print(args)
10
11 test3(1,2,3,4,5,6,7,8,9,) #这里1传给x,剩下的变成元组传给args
12
13 def test4(**kwargs): # **kwargs:把N个关键字参数转换成字典的方式
14 print(kwargs)
15 print(kwargs["name"])
16 print(kwargs["age"])
17 print(kwargs["IQ"])
18
19 test4(name="Irlo",age=26,sex="F",IQ=220)
20 test4(**{"name":'Irlo',"age":'26',"IQ":'220'})
21
22
23 def test5(name,**kwargs):
24 print(name)
25 print(kwargs)
26
27 test5("Irlo") #如果不给kwargs传东西则返回一个空字典
28 test5("hehe",age=26,IQ=220) # **kwargs不能接收位置参数
29
30
31 def test6(name,age=26,**kwargs): #参数组必须放在最后
32 print(name)
33 print(age)
34 print(kwargs)
35
36 test6("Irlo",35,IQ=220,sex="m") #默认参数可以用位置参数的方式赋值,或用关键字的方式赋值,如果不赋值则使用默认参数
37
38
39 def test7(name,age=26,*args,**kwargs):
40 print(name)
41 print(age)
42 print(args)
43 print(kwargs)
44 logger("Force")
45
46 def logger(source): #函数test7中嵌套一个函数logger,该logger的声明必须要早于函数test7的调用,否则报错
47 print("from %s" %source)
48
49 test7("Irlo",54,5,IQ=220,sex="M")