python中收集参数

 

在定义函数的时候,若实参个数不确定,形参就可以使用收集参数来“搞定”,仅需要在参数前面加上星号(*)即可。

 

1、 使用收集参数来表示形式参数时,需要在参数前加上星号。

>>> def a(*x):
    print("total %d parameter!" % len(x))
    print("second parameter:",x[1])

    
>>> a(3,8,4,7,9)
total 5 parameter!
second parameter: 8

 

2、使用参数前加星号的方法来表示未知实参个数的形式参数的时候,形参被打包为元组

>>> def a(*x):
    print("total parameter:", len(x))
    print("second parameter:", x[1])
    print(type(x))

    
>>> a("aaa","dddd","bbbb","cccc")
total parameter: 4
second parameter: dddd
<class 'tuple'>

 

3、收集参数可以和关键字参数结合使用

>>> def a(*x,y):
    print("collection parameter are:", x)
    print("key word parameter is:", y)

    
>>> a(4,2,"saaa","dddd",y = "88888")
collection parameter are: (4, 2, 'saaa', 'dddd')
key word parameter is: 88888

 

4、

在函数的定义中,收集参数前面的星号(*)起到的作用称为“打包”操作,就是将多个参数打包成一个元组的形式进行存储。

星号(*)在形式参数中的作用是打包,而在实际参数中的作用相反,起到“解包”的作用。

>>> a = "helloworld"
>>> print(*a)
h e l l o w o r l d
>>> a = (3,1,8,9,4)
>>> print(*a)
3 1 8 9 4
>>> a = ["aaa","ccc","ddd","bbb"]
>>> print(*a)
aaa ccc ddd bbb

 

posted @ 2021-03-07 11:52  小鲨鱼2018  阅读(410)  评论(0编辑  收藏  举报