1、实参与形参:

 1 def test(x,y):

2 print(x)

3 print(y)

4 test(1,2) 

小结:

x和y就是形参, 形象的参数

1和2就是实参,实际存在的参数,

形参与实参一一对应。


 

2、关键字参数调用:  test(y=1,x=2)  与形参顺序(位置)无关   

1 # 关键字参数调用:
2 def test(x,y):
3     print(x)
4     print(y)
5 test(y=1,x=2)

执行结果:


 

 3、位置参数与关键字参数混和调用            test(1,z=2,y=3)

1 def test(x,y,z):
2     print(x)
3     print(y)
4     print(z)
5 test(y=1,2,z=3)   #提示错误,关键字参数不能在位置参数前面
6 test(1,x=2,z=4)   #也会出错,1已经赋给了x,后面关键字参数又赋给了x一个值,所以出错。
7 test(1,z=2,y=3)   #这个就不会出错。

 

执行结果:

test(y=1,2,z=3)执行提示的错误如下:

  SyntaxError: positional argument follows keyword argument    

  错误解释:关键字参数不能在位置参数前面

  

 

test(1,x=2,z=4) 执行提示的错误如下:

  TypeError: test() got multiple values for argument 'x

  错误解释:X已经获得了多个值。

  

 小结:

  关键字参数不能在位置参数前面。

  位置参数和关键字参数不能为同一个形参赋多个值。

4、默认参数   

      def test(x,y=2): 这个就是默认参数

1 # 默认参数:
2 def test(x,y=2):
3     print(x)
4     print(y)
5 test(1)
6 test(1,y=4)
7 test(1,6)

默认参数的特点:

      默认参数调用函数的时候,默认参数非必须传递。函数调用时可调用可以不调用。上面的test()函数调用,test(1),test(1,y=4),test(1,6)上面这三种函数调用方式都正确。

默认参数应用场景:

      1、默认安装时

      2、设置默认值,如设置默认端口号。


 

5、非固定参数--参数组:

  应用场景:  实参不确定的情况下。

方式一:*args参数组    

1 def test(*args):
2     print(args)
3 test(1,2,3,4,5,6)
4 test(*[1,2,3,4,5,6])  #*args=*[1,2,3,4,5,6]  args=(1,2,3,4,5,6) args会将列表,元组,字典统一转换为元组

上面两个函数执行是等价的。

执行结果:

 小结:

  参数组会将参数转换为元组

  接收N个位置参数转换为元组的形式。


 

方式二: 形参与参数组组合:

def test1(x,*args):
    print(x)
    print(args)
test1(1,2,3,4,5,6)

执行结果:

小结:

  函数传参时会将1赋给x,然后剩下的传给函数组。


 

方式三:  **kwargs参数组

  将n个关键字参数转换为字典的方式。

1 def test2(**kwargs):
2     print(kwargs)
3 test2(name="alex",age=8,sex="F")
4 test2(**{"name":"zhang3","age":18,"sex":"F"})    #与上面等价,

 **kwargs =**{"name":"zhang3","age":18,"sex":"F"}    因此 kwargs={"name":"zhang3","age":18,"sex":"F"}

执行结果:

  小结:

     将n个关键字参数转换为字典的方式。


 

方式四、**kwargs与形参。 

def test3(name,**kwargs):
    print(name)
    print(kwargs)
test3("alex",age=9,sex="m")

执行结果:

 kwargs与形参小结:

     如果没有给参数组赋值,执行结果会赋一个空值。


 

方式五、形参,默认参数与**kwargs参数组结合:

1 def test4(name,age=18,**kwargs):
2     print(name)
3     print(age)
4     print(kwargs)
5 test4("alex",sex="m",hobby="car",age=10)

执行结果:

方式六、形参,默认参数,*args与**kwargs参数组结合:

1 def test4(name,age=18,*args,**kwargs):
2     print(name)
3     print(age)
4     print(args)
5     print(kwargs)
6 test4("alex",age=10,sex="m",hobby="car")

 

注意:

  1、定义函数时,不能写成这样  def test4(name,*args,**kwargs,age=18):     参数组必须要写在默认参数或形参后面。

  2、执行函数时,test4("alex",age=10,sex="m",hobby="car")     

        1、关键字参数必须要在位置参数后面

        2、*args参数组通过位置参数传参,**kwargs参数组通过关键字参数传参。

 posted on 2018-08-05 16:38  二十二a  阅读(172)  评论(0编辑  收藏  举报