其他分享
首页 > 其他分享> > 第二十四篇 可变长参数

第二十四篇 可变长参数

作者:互联网

目录

第二十四篇 可变长参数

一、预备知识

## 二、可变长形参

1.可变长形参之*

def func(*args):        # args = (2,4,6,8,10)
    num = 0
    for i in args:
        num += i
    return num

sum_int = func(2,4,6,8,10)
print(sum_int)            # 30

2.可变长形参之**

def func(**kwargs):
    print(kwargs)
    
func(a=5,name = 'king')    # {'a': 5, 'name': 'king'}

三、可变长实参

1.可变长实参之*

def func(x,y,z,*args):
    print(x,y,z,args)
    
func(*(1,2,3,4),5,6,7)   # 先打散成(1,2,3,4,5,6,7)
# 然后传给形参就变成 x=1,y=2,z=3,args=(4,5,6,7)
# 所以最后的结果是:1 2 3 (4, 5, 6, 7)

2.可变长实参之**

def func(x,y,**kwargs):
    print(x,y,kwargs)
    
func(2,3,**{'name':'king','age':20}) 
# 2,3,{'name':'king','age':20}

四、可变长参数的应用

def f1(name,age,gender):
    print(f'my name is {name},my age is {age},my gender is {gender}')
          
def f2(*args,**kwargs):
          print(f'args = {args}, kwargs = {kwargs}')
          f1(*args,**kwargs)
f2(age =20, gender ='male', name ='king') 

'''
args = (), kwargs = {'age': 20, 'gender': 'male', 'name': 'king'}
my name is king,my age is 20,my gender is male
'''

五、命名关键字形参

def f(x,y,**kwargs):
    if 'name' not in kwargs or 'age' not in kwargs:
        print('name和age必须用关键字实参进行传值')
        return
    print(kwargs['name'],kwargs['age'])
    
f(1,3,name='king',age=20)
# king 20
def f(i, *, name, gender='male', age):
    print(i)
    print(age)


f(1, x='king', age=19)  '''TypeError: register() got multiple values for argument 'x' 。也就是关键字实参传值时不能随意改关键字形参的key'''
def f(i, *, name, gender='male', age):
    print(i)
    print(age)


f(1,'king', age=19) 

六、总结

def func(*args,**kwargs):
    code

标签:args,name,age,可变,参数,kwargs,实参,二十四篇
来源: https://www.cnblogs.com/itboy-newking/p/10953488.html