Python知识分享网 - 专业的Python学习网站 学Python,上Python222
Python 函数的不定长参数
发布于:2023-09-12 10:49:45

Python 7天快速入门完整视频教程https://www.bilibili.com/video/BV1o84y1Z7J1

 

 

Python    函数的不定长参数

 

 

前面我们学过位置参数,关键字参数,默认值参数。

现在我们再学习一个不定长参数,主要用于不确定调用的时候会传递多少个参数的场景。

不定长参数的类型也分为位置传递,和关键字传递两种。

 

不定长参数(位置传递)

 

我们通过元组tuple类型的 *args 来实现,具体看下实例:

 

def test(*args):
    print(args, type(args))


test(1, "2")
test(True, 1, "2", 3.14)
test()

 

运行输出:

 

(1, '2') <class 'tuple'>
(True, 1, '2', 3.14) <class 'tuple'>
() <class 'tuple'>

 

 

不定长参数(关键字传递)

 

我们通过字典dict类型的 **kwargs 来实现,具体看下实例:

 

def test2(**kwargs):
    print(kwargs, type(kwargs))

test2(name="Jack", age=11)
test2()

 

运行输出:

 

{'name': 'Jack', 'age': 11} <class 'dict'>
{} <class 'dict'>

 

 

 

转载自: