python函数中形参中的*、**以及实参中的*、**

编程入门 行业动态 更新时间:2024-10-26 14:28:50

python<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数中形参中的*、**以及实参中的*、**"/>

python函数中形参中的*、**以及实参中的*、**

参考

  • More Control Flow Tools
  • What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

函数定义中

在函数定义中,我们可以在参数前加*,或者加**,其中加*代表接受一个像list或者tuple类型的参数,加**代表接受一个像dict一样的参数。

  • 参数有*
def fun(name, *tuple):print("name is ", name)for i in tuple:print("tuple has ", i)fun("pan", 1, 3, 'dong')

结果为:

name is  pan
tuple has  1
tuple has  3
tuple has  dong
a = (1, 2, "dong")
fun("pan", a)

结果为:

name is  pan
tuple has  (1, 2, 'dong')

可以看到,当真正传入一个tuple或者list,并不会一次输出其中的元素,而是将这整个tuple或者list看做一个元素输出。

  • 参数有**
def fun(name, **dict):print("name is ", name)for key in dict:print("dict key is", key, end=',')print("value is", dict[key])fun("pan", country="china", city="rizhao")

结果:

name is  pan
dict key is country,value is china
dict key is city,value is rizhao

可以看到,将传入的china和rizhao看做了字典的两个值,country和city看做字典的键。

dic = {"country": "china", "city": "rizhao"}
fun("pan", dic)

报错:

fun() takes 1 positional argument but 2 were given
  • 参数有*和**
    参数如果有*和**,那么*要在前面。
def fun(name, *tuple, **dict):print("name is ", name)for i in tuple:print("tuple has ", i)for key in dict:print("dict key is", key, end=',')print("value is", dict[key])fun("pan", 1, 2, 3, country="china", city="rizhao")

结果为:

name is  pan
tuple has  1
tuple has  2
tuple has  3
dict key is country,value is china
dict key is city,value is rizhao

函数调用中

函数定义如下:

def fun(name, country, city, major="cs"):print("name is", name)print("country is", country)print("city is", city)print("major is", major)
fun('pan', 'china', 'rizhao')a = ['pan', 'china', 'rizhao']
fun(*a)a = ('pan', 'china', 'rizhao')
fun(*a)a = {"name": "pan", "city": "rizhao", "country": "china"}
fun(**a)

结果均为:

name is pan
country is china
city is rizhao
major is cs

注意,在使用字典传参数时,字典的键必须和函数的形参名称对应起来。不能有冗余的键,也不能缺少键。

  • 冗余
a = {"name": "pan", "city": "rizhao", "country": "china", "temp": 23}
fun(**a)
fun() got an unexpected keyword argument 'temp'
  • 缺少
a = {"name": "pan", "city": "rizhao"}
fun(**a)
fun() missing 1 required positional argument: 'country'

更多推荐

python函数中形参中的*、**以及实参中的*、**

本文发布于:2023-07-28 17:00:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1256710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   python   实参中   中形参中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!