# 定义带有可变参数和关键字参数的函数
def show(*args, **kwargs):
# args: 元组
# kwargs: 字典
print(args)
print(kwargs)
# 下面的几步知识为了迭代查看参数的每个值,要注意的是 **kwargs 的展现实字典形式,所以要用 dict.values() 。
# for value in args:
# print(value)
#
# print("*" * 30)
#
# for value in kwargs.values():
# print(value)
# 调用带有不定长参数的函数
# show()
# 按照位置参数进行传参,该数据封装成元组给args
show(1, 3, 5)
## output
(1, 3, 5)
{}
# 按照关键字参数的方式进行差传参
show(a=2, b=4, c=6)
## output
()
{'a': 2, 'b': 4, 'c': 6}
# 前面使用位置参数后面使用关键字
show(1, 3, 5, a=2, b=4, c=6)
## output
(1, 3, 5)
{'a': 2, 'b': 4, 'c': 6}
my_tuple = (1, 3, 5)
# 需求: 把元组按照位置参数的方进行传参:*my_tuple
show(*my_tuple)
## output
(1, 3, 5)
{}
my_tuple = (1, 3, 5)
# 元组前不加 *,就会将整个元组看做一个单独的参数。
show(my_tuple)
## output
((1, 3, 5),)
{}
my_dict = {"a": 2, "b": 4, "c": 6}
# 需求: 把字典按照关键字的方式进行传参: **my_dict
# 同理,不加** 的话视字典为单独一个参数参入元组,只加一个的话将每个 key 传入元组。
show(**my_dict) # => show(a=2, b=4, c=6)
## output
()
{'a': 2, 'b': 4, 'c': 6}
my_tuple = (1, 3, 5)
my_dict = {"a": 2, "b": 4, "c": 6}
show(*my_tuple, **my_dict) # => show(1, 3, 5, a=2, b=4, c=6)
## output
(1, 3, 5)
{'a': 2, 'b': 4, 'c': 6}
可变参数 *args 和关键字参数 ** kwargs 在函数内的表现形式
最新推荐文章于 2024-04-22 16:07:30 发布