Python 函数不定长参数
生活随笔
收集整理的這篇文章主要介紹了
Python 函数不定长参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 字典形式參數
- 出現帶一個星號的參數 args,這是可變位置參數;
- 帶兩個星號的參數 kwargs,這是可變關鍵字參數。
def test(x, y, *args, **kwargs):print(x)print(y)print(args)print(kwargs)
可變表示函數被賦值的變量個數是變化的。例如,可以這樣調用函數:
test(1,2,3,4,a="hello",b="world")
輸出結果:
1
2
(3, 4)
{'a': 'hello', 'b': 'world'}
可變位置參數 args 被解析為元組,可變關鍵字參數 kwargs 被解析為字典。
2. 傳入元組和字典
def test(x, y, *args, **kwargs):print(x)print(y)print(args)print(kwargs)
可以使用下面的傳參方法調用:
a = (3,4)
d = {"a":"hello", "b":"world"}
test(1,2,*a, **d)
輸出結果:
1
2
(3, 4)
{'a': 'hello', 'b': 'world'}
總結
以上是生活随笔為你收集整理的Python 函数不定长参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 余罪百度云资源
- 下一篇: Windows Python3.6 安装