一、动态参数(不定长参数)def func(*args):
形参: 3种 动态参数
*args 动态参数,不定长参数
*rarge用法
def func(*args):
print(args,type(args))
func(1,2,‘alex‘,3,4,5,6,8,4,7,2)
结果
*args按位置对应不能放到,其他形参位置前边
def func(*args,a,b,c):
print(a)
print(b)
print(c)
print(args,type(args))
func(1,2,‘alex‘,3,4,)
结果
正确用法
def func(a,b,c,*args):
print(a)
print(b)
print(c)
print(args,type(args))
func(1,2,‘alex‘)
结果
位置参数,*args,默认参数,**kwargs
def func(a,b,c,sex = ‘男‘,*args):
print(a)
print(b)
print(c)
print(sex)
print(args,type(args))
func(1,2,‘alex‘,‘wusir‘,‘ritian ‘
结果
sex=‘男’被wusir覆盖
def func(a,b,c,*args,sex = ‘男‘):
print(a)
print(b)
print(c)
print(sex)
print(args,type(args))
func(1,2,‘alex‘,‘wusir‘,‘ritian ‘,sex=‘女‘)
结果
**kwargs的用法
def func(**kwargs): print(kwargs) func(a = 1,b = 4,c = 3,d = 2)
结果
def func(a,b,c,*args,sex = ‘男‘,**kwargs): print(a) print(b) print(c) print(sex) print(args,type(args)) print(kwargs) func(1,2,‘alex‘,‘wusir‘,‘ritian ‘,sex = ‘女‘,name = ‘taibai‘,age = 21)
结果
*args,**kwargs万能参数
def func2(*args,**kwargs): #万能参数 print(args) print(kwargs) func2(1,2,3,5,name=‘alex‘,age=56)
结果
*rags加法计算器
def my_sum(*args): count = 0 for i in args: count += i return count print(my_sum(1,2,3,6,78)) print(sum([1,2,3]))
结果
*魔法运算:打散
def func2(*args,**kwargs): print(args) #(1,2,3) l1 = [1,2,3,] l2 = [1,2,3,2,3,100,2] func2(*l2,*l1)
结果
def func3(*args,**kwargs): print(args) print(kwargs) dic = {‘name‘:‘alex‘,‘age‘:12} dic2 = {‘name‘:‘jin‘,‘age‘:22} func3(**{‘name1‘:‘alex‘,‘age1‘:12},**{‘name2‘:‘jin‘,‘age2‘:22},name3 = ‘wusir‘)
结果
def func3(*args,**kwargs): print(args) print(kwargs) dic = {‘name‘:‘alex‘,‘age‘:12} dic2 = {‘name‘:‘jin‘,‘age‘:22} func3(**{‘name1‘:‘alex‘,‘age1‘:12},**{‘name2‘:‘jin‘,‘age2‘:22},name3 = ‘wusir‘)
结果
args元组,他包含了你所有的位置参数.
**kwargs 他包含了关键动态参数