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

参考

函数定义中

在函数定义中,我们可以在参数前加*,或者加**,其中加*代表接受一个像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'

猜你喜欢

转载自blog.csdn.net/qq_43219379/article/details/123720231